Tag Archives: leetcode

ADS1.2 Error: cannot obtain license [How to Solve]

The error is as follows

Modify the license content under the licenses file:
modify it to the following content.

#
# Generated on 2021-dec-1 by licwizard
#
PACKAGE ads armlmd 1.200 E32F0DE5161D COMPONENTS="armasm compiler bats armulate axd adwu fromelf armlink codewarrior armsd"
INCREMENT ads armlmd 1.200 permanent uncounted 612C53EF47C7 HOSTID=ANY ISSUER="Full License by armer, only for educational purpose!" ck=0
FEATURE Win32_CWIDE_Unlimited metrowks 4.2 permanent uncounted D8C287BC5B1B HOSTID=ANY

[Solved] Leetcode Error: AddressSanitizer: SEGV on unknown address 0x55eb765425b8 (pc 0x55eb76542b86 bp 0x7ffd1bd2

Hi, I’ve come back to the article ᕕ (ᐛ) ᕗ
recently, I’m brushing leetcode, and there’s an error report about stack

 AddressSanitizer:DEADLYSIGNAL
=================================================================
==42==ERROR: AddressSanitizer: SEGV on unknown address 0x55eb765425b8 (pc 0x55eb76542b86 bp 0x7ffd1bd27d50 sp 0x7ffd1bd27d00 T0)
==42==The signal is caused by a WRITE memory access.
    #2 0x7fe2bd0fe0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
AddressSanitizer can not provide additional info.
==42==ABORTING

My code is as follows



bool isValid(char * s){
    bool answer;
    int i=0;
    char tem;
    stack S=creatstack;  //Something is wrong here, it should be a function but I forgot to add the brackets
    while(s[i]!='\0'){
        if(s[i]=='('||s[i]=='['||s[i]=='{') push(s[i],S);
        else{
            tem=pop(S);
            if((tem=='('&&s[i]==')')||(tem=='['&&s[i]==']')||(tem=='{'&&s[i]=='}')) ;
            else return false;
        }
        i++;
    }
    return true;
}

Change to

stack S=creatstack();

After that, the problem was solved

Leetcode error: address sanitizer: detailed analysis and solution of deadlysignal

Leetcode error: address sanitizer: detailed analysis and solution of deadlysignal

Problem description, problem analysis, case analysis, error source code, OK code after source code analysis and solution

For more summary, please refer to: C brush questions: leetcode brush questions step on the pit common bug summary

Problem description


Error: addresssanitizer: deadlysignal, details are as follows

===42====ERROR:AddressSanitizer: SEGV on unknown address xx. 
The signal is caused by a READ memory access.

Problem analysis


In general, there may be the following problems:

Out of bounds, the array reference exceeds the left and right bounds, infinite recursion, the code can not normally end, return function input and output parameters, return processing error

According to the above ideas, the example code is analyzed to solve the bug.

Case analysis


The questions come from leetcode topic 46. Please refer to the problem analysis blog for details. Paste the problem code of the above error in the first edition:

Error source code

Main key code of the first layer:

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int g_trackNum; // Used for temporary stacking during recursive calls
int g_rowPos;

// Subfunction declaration
int isContanin(int *nums, int len, int val);
void backtrack(int *nums, int numsSize, int **returnColumnSizes, int *track);

// Main call function
int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
{
    // Calculate all possible totals
    int row = 1, i;
    for (i = numsSize; i > 0; i--) {
        row *= i;
    }
    *returnSize = row;

    printf("row = %d\n", row);

    // Request a two-dimensional array of the corresponding size and allocate space
    returnColumnSizes = (int **)malloc((row + 10) * sizeof(int*));
    if (returnColumnSizes == NULL) {
        return NULL;
    }
    int *p;
    for (i = 0; i < row; i++) {
        p = (int*)malloc((numsSize + 10) * sizeof(int));
        if (p == NULL) {
            return NULL;
        }
        returnColumnSizes[i] = p;
    }
    p = (int*)malloc(numsSize * sizeof(int));
    if (p == NULL) {
        return NULL;
    }
    int *track = p;

    // Backtrack to exhaust all possible permutations
    g_trackNum = 0;
    g_rowPos = 0;
    backtrack(nums, numsSize, returnColumnSizes, track); // Put the result from line 0

    // Returns returnSize and a two-dimensional pointer
    return returnColumnSizes;
}

Recursive code for backtracking implementation:

void backtrack(int *nums, int numsSize, int **returnColumnSizes, int *track)
{
    // Reach the leaf node track join returnColumSizes, the recorded path has been equal to the length of the array stop
    int i;
    if (g_trackNum == numsSize) {
        // printf("back: g_rowPos = %d\n", g_rowPos);
        for (i = 0; i < numsSize; i++) {
            // printf("back: g_rowPos = %d\n", g_rowPos);
            returnColumnSizes[g_rowPos][i] = track[i];
        }
        g_rowPos++;
        return;
    }

    // Recursive traversal
    for (i = 0; i < numsSize; i++) {
        // check if the current value is in the track
        if (isContanin(track, g_trackNum, nums[i])) {
            continue;
        }

        // If not, join track
        // printf("back: g_trackNum = %d\n", g_trackNum);
        track[g_trackNum++] = nums[i];
        
        // Continue traversing backwards
        backtrack(nums, numsSize, returnColumnSizes, track);
        // After the node returns, retrieve the value in the track
        g_trackNum--;
    }

    return;
}

Sub function to determine whether the current value has been traversed

int isContanin(int *nums, int len, int val)
{
    int flag = 0;
    int i;
    for (i = 0; i < len; i++) {
        if (nums[i] == val) {
            flag = 1;
            break;
        }
    }
    return flag;
}

Source code analysis

check possible problem 1 : out of bounds, array reference out of bounds

There are two main ideas:
1. Try to allocate enough space first to see if it is a space problem
2. Print subscript value in advance where it may cross the boundary to see if it overflows. Because address disinfection is interrupted at runtime, you can use printf to print the situation before the interruption.

Method 1

At each possible cross-border reference, the subscript is printed in advance to record the subscript coefficient printed before the program crashes. An example of the printing code is as follows: printf ("row = D/N", row)printf("back: g_ rowPos = %d\n", g_ rowPos);printf("back: g_ trackNum = %d\n", g_ trackNum);

Method 2

When initializing the array allocation space, forcibly allocates enough space to ensure that the space is sufficient. If there is no error after increasing the space, it means that the array reference is out of bounds

After running the code, it was found that subscript printing was normal, and no problem was found, so we continued to investigate possible problem 2.

check possible problem 2 : infinite recursion, the code can’t end and return normally

Print the output record directly in the termination condition of the recursive function backtrack, and observe whether the recursion is carried out according to the expected recursion mode. If there is no print record, then the function is not terminated and recursion is infinite all the time

After running the code, it is found that there is no such problem.

check possible problem 3 : error in the return processing of function input and output parameters
after carefully reading the input and output instructions of the first line of the code and comparing the implementation of online C code, it is found that the understanding of output parameters is wrong.

Variable secondary pointer returncolumnsizes stores the number of columns output in each row. Although the number of columns in the title is fixed, it needs to be assigned to the corresponding number of columns. And I first understood that this is the return pointer of a two-dimensional array. The return pointer of the two-dimensional array is passed through the function return parameter. The first address of the two-dimensional array allocated by direct return can be used.

After modifying the above problems, the code output is normal and no error is reported.

OK code after solution

// Determine if an element has been traversed
int isContain(int *nums, int len, int val)
{
    int flag = 0;
    int i;
    for (i = 0; i < len; i++) {
        if (nums[i] == val) {
            flag = 1;
            break;
        }
    }
    return flag;
}

// Note that this global variable is best defined by declaration only and initialized before backtrack
// in case the LeetCode judge does not re-initialize it, resulting in a miscalculation
int g_trackNum; // Used for temporary stacking during recursive calls
int g_rowPos; // Record each row

void backtrack(int *nums, int numsSize, int **returnColumnSizes, int *track)
{
    // Reach the leaf node track join returnColumSizes, the recorded path has been equal to the length of the array stop
    int i;
    if (g_trackNum == numsSize) {
        for (i = 0; i < numsSize; i++) {
            returnColumnSizes[g_rowPos][i] = track[i];
        }
        g_rowPos++;
        return;
    }

    // Recursive traversal
    for (i = 0; i < numsSize; i++) {
        // check if the current value is in the track
        if (isContain(track, g_trackNum, nums[i])) {
            continue;
        }

        // If not, add track
        track[g_trackNum++] = nums[i];
        // continue traversing backwards
        backtrack(nums, numsSize, returnColumnSizes, track);
        // After the node returns, retrieve the value in track
        g_trackNum--;
    }

    return;
}

int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
{
    // Calculate the total number of all possible n!
    int row = 1, i;
    for (i = numsSize; i > 0; i--) {
        row *= i;
    }
    *returnSize = row;

    // Calculate the number of columns in each row of the returned array
    *returnColumnSizes = (int *)malloc(sizeof(int) * (*returnSize));
    if (returnColumnSizes == NULL) {
        return NULL;
    }
    for (int i = 0; i < row; i++) {
        returnColumnSizes[0][i] = numsSize;
    }

    // Request a two-dimensional array of the corresponding size and allocate space
    int **res = (int **)malloc((row + 10) * sizeof(int*));
    if (res == NULL) {
        return NULL;
    }
    int *p;
    for (i = 0; i < row; i++) {
        p = (int*)malloc((numsSize + 10) * sizeof(int));
        if (p == NULL) {
            return NULL;
        }
        res[i] = p;
    }
    p = (int*)malloc(numsSize * sizeof(int));
    if (p == NULL) {
        return NULL;
    }
    int *track = p;

    // Backtrack to exhaust all possible permutations
    g_trackNum = 0;
    g_rowPos = 0;
    backtrack(nums, numsSize, res, track); // put the result from row 0

    return res;
}

LeetCode 23. Merge k Sorted Lists(java)

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Solution 1: use heap to do it. First, put the first element of K lists into heap. After each poll, put it into the next element of the poll until the heap is empty. The time complexity is O (mklogk), and the space complexity is O (k)

public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        if (lists.length == 1) return lists[0];
        PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });
        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) queue.add(lists[i]);
        }
        ListNode dummy = new ListNode(-1), cur = dummy;
        while (!queue.isEmpty()) {
            ListNode temp = queue.poll();
            cur.next = temp;
            cur = temp;
            if (temp.next != null) queue.add(temp.next);
        }
        return dummy.next;
    }

Solution 2: the idea of merge sort is better than solution 1. List merges in pairs each time, until the merges into a list, the time complexity is O ((M / 2) (K / 2 + K / 4 + K / 8 +…) )It is O (kmlogk), but it has a constant number of optimizations than method one. The space complexity is O (1)

public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        int begin = 0, end = lists.length - 1;
        while (begin < end) {
            int mid = (begin + end - 1) / 2;
            for (int i = 0; i <= mid; i++) {
                lists[i] = merge2list(lists[i], lists[end - i]);
            }
            end = (begin + end) / 2;
        }
        return lists[0];
    }
    public ListNode merge2list(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) return null;
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummy = new ListNode(-1), cur = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                cur = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                cur = l2;
                l2 = l2.next;
            }
        }
        if (l1 != null) cur.next = l1;
        if (l2 != null) cur.next = l2;
        return dummy.next;
    }

LeetCode 332. Reconstruct Itinerary

Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
idea:
we have a list of edges, each node pair represents for [from, to]. and that are the series of tickets
and we know that the journel starts with JFK, we need to resort it and return with the nodes in order.
example:
Input: [[“JFK”,“SFO”],[“JFK”,“ATL”],[“SFO”,“ATL”],[“ATL”,“JFK”],[“ATL”,“SFO”]]
Output: [“JFK”,“ATL”,“JFK”,“SFO”,“ATL”,“SFO”]
Explanation: Another possible reconstruction is [“JFK”,“SFO”,“ATL”,“JFK”,“ATL”,“SFO”].
But it is larger in lexical order.
there are four instructions:
1 If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary [“JFK”, “LGA”] has a smaller lexical order than [“JFK”, “LGB”].
2 All airports are represented by three capital letters (IATA code).
3 You may assume all tickets form at least one valid itinerary.
4 One must use all the tickets once and only once.

public List<String> findItinerary(List<List<String>> tickets)

I’m still trying to solve this using BFS, each time I only choose one neighbor to go, the one with smallest lexi order. so it’s bascally dfs but I’m too lazy to even think about how to write this in dfs.
but sadly, it’s MLE

class Solution {
    public List<String> findItinerary(List<List<String>> tickets) {
        HashMap<String, List<String>> map = new HashMap<>();
        
        for (List<String> ticket: tickets) {
            map.computeIfAbsent(ticket.get(0), k -> new ArrayList<>());
            map.get(ticket.get(0)).add(ticket.get(1));
        }
        // we will using bfs but each time we only go with negihbor with minimum lexi, although for situations like this, it's better for us to implement dfs instead of bfs
        Queue<String> queue = new LinkedList<>();
        queue.offer("JFK");
        List<String> res = new ArrayList<>();
        res.add("JFK");
        //i don;t think visited will be useful, because we might revisited previous node, like we might need to return the JFK again in example
        while (!queue.isEmpty()) {
            String cur = queue.poll();
            if (!map.containsKey(cur)) { //we neeed to check if map contains this key in case it is the last one
                break;
            }
            int size = map.get(cur).size();
            String min = "ZZZ";
            for (int i = 0; i < size; i++) {
                if (map.get(cur).get(i).compareTo(min) < 0) {
                    min = map.get(cur).get(i);
                }
            }
            queue.offer(min);
            res.add(min);
        }
        return res;
    }
}

So we using DFS:
/ / why can DFS guarantee to travel all the edges and only once?

class Solution {
    public List<String> findItinerary(List<List<String>> tickets) {
        HashMap<String, PriorityQueue<String>> map = new HashMap<>();
        
        for (List<String> ticket: tickets) {
            map.computeIfAbsent(ticket.get(0), k -> new PriorityQueue<>()).add(ticket.get(1));
        }
        List<String> route = new LinkedList<>();
        dfs(map, route, "JFK"); 
        return route;
    }
    
    private void dfs(HashMap<String, PriorityQueue<String>> map, List<String> route, String node) {
        while (map.containsKey(node) && !map.get(node).isEmpty()) { //if we can move forward 
            dfs(map, route, map.get(node).poll());
        }
        route.add(0, node); //alwatys added to the head of this route list
    }
}

Of course, we can write DFs in an iterative way

public List<String> findItinerary(String[][] tickets) {
    Map<String, PriorityQueue<String>> targets = new HashMap<>();
    for (String[] ticket : tickets)
        targets.computeIfAbsent(ticket[0], k -> new PriorityQueue()).add(ticket[1]);
    List<String> route = new LinkedList();
    Stack<String> stack = new Stack<>();
    stack.push("JFK");
    while (!stack.empty()) {
        while (targets.containsKey(stack.peek()) && !targets.get(stack.peek()).isEmpty())
            stack.push(targets.get(stack.peek()).poll());
        route.add(0, stack.pop());
    }
    return route;
}

Binary tree traversal (preorder, middle order, postorder, hierarchy traversal, depth first, breadth first)

Binary tree is a very important data structure, many other data structures are based on the evolution of binary tree. For binary tree, there are depth traversal and breadth traversal. Depth traversal has three traversal methods: preorder, middle order and postorder. Breadth traversal is what we usually call level traversal. Because the definition of tree itself is a recursive definition, it is not only easy to understand but also very concise to use the recursive method to realize the three traversal of tree. For breadth traversal, it needs the support of other data structures, such as heap. Therefore, for a piece of code, readability is sometimes more important than the efficiency of the code itself.

The four main traversal ideas are as follows

Preorder traversal: root node — & gt; left subtree — & gt; right subtree

Middle order traversal: left subtree — & gt; root node — & gt; right subtree

Postorder traversal: left subtree — & gt; right subtree — & gt; root node

Level traversal: just traverse by level

For example, find the following binary tree traversal

Preorder traversal: 1.2.4.5.7.8.3.6

Middle order traversal: 4 ﹣ 2 ﹣ 7 ﹣ 5 ﹣ 8 ﹣ 1 ﹣ 3 ﹣ 6

Postorder traversal: 4 ﹣ 7 ﹣ 8 ﹣ 5 ﹣ 2 ﹣ 6 ﹣ 3 ﹣ 1

Level traversal: 1 ﹣ 2 ﹣ 3 ﹣ 4 ﹣ 5 ﹣ 6 ﹣ 7 ﹣ 8

1、 Preorder traversal

1) According to the traversal idea mentioned above: root node — & gt; left subtree — & gt; right subtree, it is easy to write recursive version:

public void preOrderTraverse1(TreeNode root) {
		if (root != null) {
			System.out.print(root.val+"  ");
			preOrderTraverse1(root.left);
			preOrderTraverse1(root.right);
		}
	}

2) Now let’s talk about the non recursive version:

According to the order of preorder traversal, first visit the root node, then visit the left and right subtree. Therefore, for any node, the first part is to access it directly, and then repeat the above steps when judging whether the left subtree is empty or not until it is empty. If it is empty, you need to access the right subtree. Note that after accessing the left child, you need to access the right child in turn. Therefore, you need the support of stack as a data structure. For any node, the specific steps are as follows:

a) Access it, and put the node into the stack, and set the current node as the left child;

b) Judge whether the node node is empty. If it is empty, take out the top node of the stack and leave the stack, and set the right child as the current node; otherwise, repeat step a) until the current node is empty or the stack is empty (it can be found that the nodes in the stack are stored just to access the right child)

The code is as follows:

public void preOrderTraverse2(TreeNode root) {
		LinkedList<TreeNode> stack = new LinkedList<>();
		TreeNode pNode = root;
		while (pNode != null || !stack.isEmpty()) {
			if (pNode != null) {
				System.out.print(pNode.val+"  ");
				stack.push(pNode);
				pNode = pNode.left;
			} else { //pNode == null && !stack.isEmpty()
				TreeNode node = stack.pop();
				pNode = node.right;
			}
		}
	}

2、 Middle order traversal

1) According to the above traversal idea: left subtree — & gt; root node — & gt; right subtree, it is easy to write recursive version:

public void inOrderTraverse1(TreeNode root) {
		if (root != null) {
			inOrderTraverse1(root.left);
			System.out.print(root.val+"  ");
			inOrderTraverse1(root.right);
		}
	}

2) non recursive implementation, with the explanation of the preceding order, the middle order is relatively simple, the same reason. It’s just that the order of access is moved to the time of stack exit. The code is as follows:

public void inOrderTraverse2(TreeNode root) {
		LinkedList<TreeNode> stack = new LinkedList<>();
		TreeNode pNode = root;
		while (pNode != null || !stack.isEmpty()) {
			if (pNode != null) {
				stack.push(pNode);
				pNode = pNode.left;
			} else { //pNode == null && !stack.isEmpty()
				TreeNode node = stack.pop();
				System.out.print(node.val+"  ");
				pNode = node.right;
			}
		}
	}

3、 Postorder traversal

1) According to the traversal idea mentioned above: left subtree — & gt; right subtree — & gt; root node, it is easy to write recursive version:

public void postOrderTraverse1(TreeNode root) {
		if (root != null) {
			postOrderTraverse1(root.left);
			postOrderTraverse1(root.right);
			System.out.print(root.val+"  ");
		}
	}

2) Non recursive code, not to write

4、 Level traversal

Hierarchy traversal code is relatively simple, just need a queue, first add the root node in the queue. Then, for any node, when it is out of the queue, it can be accessed. At the same time, if the left child and the right child are not empty, enter the queue. The code is as follows:

public void levelTraverse(TreeNode root) {
		if (root == null) {
			return;
		}
		LinkedList<TreeNode> queue = new LinkedList<>();
		queue.offer(root);
		while (!queue.isEmpty()) {
			TreeNode node = queue.poll();
			System.out.print(node.val+"  ");
			if (node.left != null) {
				queue.offer(node.left);
			}
			if (node.right != null) {
				queue.offer(node.right);
			}
		}
	}

5、 Depth first traversal

In fact, depth traversal is the pre order, middle order and post order above. But in order to ensure that it corresponds to breadth first traversal, it is also written here. The code is also easy to understand. In fact, it is preorder traversal. The code is as follows:
0

public void depthOrderTraverse(TreeNode root) {
		if (root == null) {
			return;
		}
		LinkedList<TreeNode> stack = new LinkedList<>();
		stack.push(root);
		while (!stack.isEmpty()) {
			TreeNode node = stack.pop();
			System.out.print(node.val+"  ");
			if (node.right != null) {
				stack.push(node.right);
			}
			if (node.left != null) {
				stack.push(node.left);
			}
		}
	}

Finally finished!

Leetcode 832. Flip image

Answer key
They’re very clear, so do what they say, flip it horizontally first, and then flip it backwards.
Horizontal reverse can use its own reverse, reverse directly and 1 XOR can be.
code

class Solution {
public:
    vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
        int n = A.size();
        for(int i = 0; i < n; i++){
            reverse(A[i].begin(),A[i].end());
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < A[0].size(); j++){
                A[i][j] = A[i][j]^1;
            }
        }
        return A;
    }
};

Leetcode-234: palindrome linked list

Topic describes
Determine whether a linked list is a palindrome list.
// 1 2 nil
// 1 2 1 nil
// 1 2 2 1 nil
Thought analysis
The fast and slow pointer finds the midpoint of the linked list and splits the midpoint and reverses the tail list to compare whether the values of the head and tail list are equal in turn
Code implementation

func isPalindrome(head *ListNode) bool {
	if head == nil {
		return true
	}
	fast := head.Next
	slow := head
	for fast != nil && fast.Next != nil {
		fast = fast.Next.Next
		slow = slow.Next
	}

	tail := reverse(slow.Next)
	slow.Next = nil

	for head != nil && tail != nil {
		if head.Val != tail.Val {
			return false
		}
		head = head.Next
		tail = tail.Next
	}
	return true
}

func reverse(head *ListNode) *ListNode {
	if head == nil {
		return head
	}
	var pre *ListNode
	for head != nil {
		temp := head.Next
		head.Next = pre
		pre = head
		head = temp
	}
	return pre
}

Java.lang.Character . isdigit() and isletter() methods

[LeetCode] – 125. The Valid Palindrome
In this problem, I encountered a new method to determine whether a string is a letter or a number. Here’s an explanation.
Use isDigit to determine if it is a number

public static boolean isNumeric(String str){
    for (int i = str.length();--i>=0;){
    if (!Character.isDigit(str.charAt(i))){
        return false;
    }
  }
  return true;
}

Use isLetter to determine if it is a letter

public class Test{
   public static void main(String args[]){
      System.out.println( Character.isLetter('c'));
      System.out.println( Character.isLetter('5'));
   }
}

Results:

 true
 false

21. Merge Two Sorted Lists [easy] (Python)

Topic link
https://leetcode.com/problems/merge-two-sorted-lists/
The questions in the original

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

The title translation
Merge the two ordered lists and return the new list. The new list should be the result of splicing two old lists.
Thinking method
Thinking a
After merging, the linked list is still in order. Two linked lists can be traversed at the same time. Each time, the nodes with smaller values in the two lists are selected and connected in turn to obtain the final linked list.
code

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 or not l2:
            return l1 or l2
        head = cur = ListNode(0)
        while l1 and l2:
            if l1.val < l2.val:
                cur.next = l1
                l1 = l1.next
            else:
                cur.next = l2
                l2 = l2.next
            cur = cur.next
        cur.next = l1 or l2
        return head.next

Idea 2
Similar idea one, you can take the linked list with a smaller head node as a reference, and insert the nodes in another linked list into the linked list according to the size, forming a large ordered linked list
code

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 or not l2:
            return l1 or l2
        head = small = l1 if l1.val < l2.val else l2
        big = l1 if l1.val >= l2.val else l2
        pre = None
        while big:
            if not small:
                pre.next = big
                break
            if big.val >= small.val:
                pre = small
                small = small.next
            else:
                tmp = big.next
                pre.next = big
                pre = big
                big.next = small
                big = tmp
        return head

Thought three
Let’s think recursively.
code

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 or not l2:
            return l1 or l2
        if l1.val < l2.val:
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2

PS: The novice brush LeetCode, the new handwriting blog, write wrong or write unclear please help point out, thank you!
reprint please indicate the: http://blog.csdn.net/coder_orz/article/details/51529359

[sum of code] report


personal blog: http://fuxuemingzhu.cn/


directory
Double pointer list generation loop
The date of

Title address: https://leetcode.com/problems/sum-of-square-numbers/discuss/
Topic describes
Given a non-negative integer c, your task is to decide whether there’s two integers a and b such that a2 + b2 = c.
Example 1:

Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: 3
Output: False

Subject to
Can a number consist of the sum of squares of two Numbers?
The problem solving method
Double pointer
The two Pointers are closer to the center, so it’s easier to understand.

class Solution(object):
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        left = 0
        right = int(c ** 0.5)
        while left <= right:
            cur = left ** 2 + right ** 2
            if cur < c:
                left += 1
            elif cur > c:
                right -= 1
            else:
                return True
        return False
                      

List generation
Xrange is a spanning form, and range returns a list. Determine if the number left after removing a square is a square.

class Solution(object):
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        def is_square(N):
            return int(N ** 0.5) ** 2 == N
        
        return any(is_square(c - a ** 2) for a in xrange(int(c ** 0.5) + 1))                

cycle
Use the loop to see if there is an A, so that c minus a squared is a perfect square.
There are a lot of ways to tell if something is a perfect square, but I’m going to use the simplest way, which is to take the square root and then square it to see if it’s equal.
The Python solution is as follows:

class Solution(object):
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        if c == 0: return True
        for a in range(1, int(math.sqrt(c) + 1)):
            b = c - a * a
            if int(math.sqrt(b)) ** 2 == b:
                return True
        return False

C++ solution is as follows:

class Solution {
public:
    bool judgeSquareSum(int c) {
        if (c == 0) return true;
        for (int a = 1; a < (int) sqrt(c) + 1; ++a){
            double b = sqrt(c - a * a);
            if (b == (int) b){
                return true;
            }
        }
        return false;
    }
};

The date of
August 24, 2017
November 24, 2018 — starting on Sunday! A week has passed