1, Introduction to algorithm
1. Simple version
2022-1-11
704. Binary search
Topics and examples
Given an n-element ordered (ascending) integer array nums and a target value target, write a function to search the target in nums. If the target value exists, return the subscript, otherwise return - 1.
Example 1:
Input: num = [- 1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 appears in nums with subscript 4
Example 2:
Input: num = [- 1,0,3,5,9,12], target = 2
Output: - 1
Explanation: 2 does not exist in nums, so - 1 is returned
code:
class Solution { public int search(int[] nums, int target) { int begin=0; int end=nums.length-1; int mid; while(begin<=end){ mid=(begin+end)/2; if(target>nums[mid]){ begin=mid+1; }else if(target<nums[mid]){ end=mid-1; }else{ return mid; } } return -1; } }
Solution:
- Binary search embodies the idea of divide and conquer,
- In the title, it is said that the array is in ascending order, that is, it is orderly, so there is no need to sort, which reduces the difficulty.
- Set the starting subscript to 0 and the ending subscript to array length - 1 (num.length-1), so as to get mid=(begin+end)/2
- Compare target with num [mid]. If target > num [mid], then target is in the upper part of the array, so begin=mid+1; If target < num s [mid], target is in the lower part of the array; If target=nums[mid], the array index is returned.
- Loop all the time. The termination condition is begin > end. If it cannot be found, it returns - 1
- The time complexity is O(log2n), and the space complexity is O(1)
278. First wrong version (※)
Topics and examples
You are a product manager and are currently leading a team to develop new products. Unfortunately, the latest version of your product has not passed the quality test. Since each version is developed based on the previous version, all versions after the wrong version are wrong.
Suppose you have n versions [1, 2,..., n], you want to find the first wrong version that causes errors in all subsequent versions.
You can call the bool isBadVersion(version) interface to determine whether the version number is wrong in the unit test. Implement a function to find the first wrong version. You should minimize the number of calls to the API.
Example 1:
Input: n = 5, bad = 4
Output: 4
Explanation:
Call isbadversion (3) - > false
Call isbadversion (5) - > true
Call isbadversion (4) - > true
Therefore, 4 is the first wrong version.
Example 2:
Input: n = 1, bad = 1
Output: 1
Tip: 1 < = bad < = n < = 231 - 1
Error code (time complexity is too high, timeout)
/* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class Solution extends VersionControl { public int firstBadVersion(int n) { int first=1; int last=n; int result=1; if(n==1){ result=1; }else{ while(first+1<=last){ int mid=(first+last)/2; if(isBadVersion(mid)&&isBadVersion(mid+1)){ last=mid; }else if((!isBadVersion(mid))&&(!isBadVersion(mid+1))){ first=mid; }else if((!isBadVersion(mid))&&isBadVersion(mid+1)){ result=mid+1; break; } } } return result; } }
Correct code
/* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class Solution extends VersionControl { public int firstBadVersion(int n) { int first=1; int last=n; while(first<last){//Cycle until the left and right ends are the same int mid=first+(last-first)/2;//Prevent overflow during calculation if(isBadVersion(mid)){ last=mid;//[first,mid] }else { first=mid+1;//[mid+1,last] } } return first;//first==last } }
Solution:
- First of all, the topic mentioned to minimize the number of calls to the API, that is, less calls to the isBadVersion(version) function. But in the error code, I called this function six times, which will increase the time. Because I always think that the previous version must be false and the latter version must be true.
- In the correct code, the first wrong version is not found in the while loop, but by narrowing the interval, there is only one (first=last), and first or last is the first wrong version.
- The most important point is that I submitted it several times, all of which timed out. The reason is that both bad and bad are big
(1 < = bad < = n < = 231 - 1), mid cannot be directly equal to (first+last)/2, but must be equal to first + (last first) / 2 to prevent overflow during calculation.
374. Guess the size of the number (the same solution as 278. The first wrong version)
Topics and examples
The rules of the number guessing game are as follows:
In each round of the game, I will choose a number randomly from 1 to n. Please guess which number you chose.
If you guess wrong, I'll tell you whether the number you guessed is larger or smaller than the number I chose.
You can call a predefined interface int guess(int num) to get the guess result. There are three possible return values (- 1, 1 or 0):
-1: The number I chose is smaller than your guess. Pick < num
1: The number I chose is bigger than you guessed
0: the number I chose is the same as you guessed. congratulations! Bingo! pick == num
Return the number I selected.
Example 1:
Input: n = 10, pick = 6
Output: 6
Example 2:
Input: n = 1, pick = 1
Output: 1
Tip: 1 < = n < = 2 ^ 31 - 1 < = pick < = n
code:
public class Solution extends GuessGame { public int guessNumber(int n) { int first=1; int last=n; while(first<last){ int mid=first+(last-first)/2; if(guess(mid)<=0){ last=mid;//[first,mid] }else{ first=mid+1;//[mid+1,last] } } return first;//first=end } }
35. Search insertion position
Topics and examples
Given a sort array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, return the position where it will be inserted in order.
You must use an algorithm with a time complexity of O(log2 n).
Example 1:
Input: num = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: num = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: num = [1,3,5,6], target = 7
Output: 4
Example 4:
Input: num = [1,3,5,6], target = 0
Output: 0
code
class Solution { public int searchInsert(int[] nums, int target) { int begin=0; int end=nums.length-1; int mid; while(begin<=end){ mid=(begin+end)/2; if(target>nums[mid]){ begin=mid+1; }else if(target<nums[mid]){ end=mid-1; }else{ return mid; } } return begin; } }
Problem solution
- This question is similar to 704 binary search. The difference is that if the target number is not found, the subscript that should be inserted will be output, which is exactly begin.
- The time complexity is O(log2n), and the space complexity is O(1)
2022-1-12
977. Square of ordered array
Topics and examples
Give you an integer array nums sorted in non decreasing order, and return a new array composed of the square of each number. It is also required to sort in non decreasing order.
Example 1:
Input: num = [- 4, - 1,0,3,10]
Output: [0,1,9,16100]
Explanation: after squaring, the array becomes [16,1,0,9100]
After sorting, the array becomes [0,1,9,16100]
Example 2:
Input: num = [- 7, - 3,2,3,11]
Output: [4,9,9,49121]
code:
class Solution { public int[] sortedSquares(int[] nums) { int []a=new int[nums.length]; for(int i=0;i<nums.length;i++){ a[i]=nums[i]*nums[i]; } Arrays.sort(a); return a; } }
Problem solution
- Square it first, and then use the arrays. java comes with Sort function.
- The time complexity is O(n), and the space complexity is O(n)
189. Rotation array
Topics and examples
Give you an array, rotate the elements in the array K positions to the right, where k is a non negative number.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
Turn right for one step: [7,1,2,3,4,5,6]
Rotate right for 2 steps: [6,7,1,2,3,4,5]
Rotate right for 3 steps: [5,6,7,1,2,3,4]
Example 2:
Input: num = [- 1, - 100,3,99], k = 2
Output: [3,99, - 1, - 100]
Explanation:
Turn right for one step: [99, - 1, - 100,3]
Rotate right for 2 steps: [3,99, - 1, - 100]
Tips:
1 <= nums.length <= 105
-2^31 <= nums[i] <= 2^31 - 1
0 <= k <= 105
code
class Solution { public void rotate(int[] nums, int k) { int []a=new int[nums.length]; int n=nums.length; for(int i=0;i<n;i++){ a[(i+k)%n]=nums[i]; } //for(int i=0;i<n;i++){ // nums[i]=a[i]; //} // System.out.print("["); // for(int j=0;j<n;j++){ // System.out.print(nums[j]); // if(j!=n-1){ // System.out.print(","); // } // } // System.out.print("]"); System.arraycopy(a,0,nums,0,n);//Shallow copy, assign the a array to the num array } }
Solution:
- I made a mistake in this question, thinking that as long as a[(i+k)%n]=nums[i], you can enter array a, but you have to assign array a to nums
- I use the for loop output. See the official solution, system arraycopy(a,0,nums,0,n);
- System provides a native static method arraycopy(), which can be used to copy arrays. For one-dimensional arrays, this copy attribute value is passed, and the modified copy will not affect the original value. When an object is stored in a two-dimensional or one-dimensional array, the copy result is a one-dimensional reference variable passed to the one-dimensional array of the copy. Modifying the copy will affect the original array.
- public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
src represents the source array, srcPos represents the starting position of the source array to be copied, desc represents the target array, destPos represents the starting position of the m target array to be copied, and length represents the length to be copied. - The time complexity is O(n), and the space complexity is O(n)
283. Move zero
Topics and examples
Given an array num, write a function to move all zeros to the end of the array while maintaining the relative order of non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
explain:
You must operate on the original array and cannot copy additional arrays.
Minimize the number of operations.
code:
class Solution { public void moveZeroes(int[] nums) { for(int i=0;i<nums.length;i++){ for(int j=i;j<nums.length;j++){ if(nums[i]==0&&nums[j]!=0){ nums[i]=nums[j]; nums[j]=0; break; } } } } }
Solution:
- Double for loop, encounter 0, and then encounter a number that is not 0, then exchange.
- Not applicable to arrays with large length
- The time complexity is O (n), and the space complexity is O(1)
2022-1-13
344. Reverse string
Topics and examples
Write a function that inverts the input string. The input string is given as a character array s.
Do not allocate additional space to another array. You must modify the input array in place and use the additional space of O(1) to solve this problem.
Example 1:
Input: s = ["h", "e", "l", "l", "o"]
Output: ["o", "l", "l", "e", "h"]
Example 2:
Input: s = ["H", "a", "n", "n", "a", "H"]
Output: ["H", "a", "n", "n", "a", "H"]
Tips:
1 <= s.length <= 105
s[i] are printable characters in the ASCII code table
code:
class Solution { public void reverseString(char[] s) { for(int i=0;i<s.length/2;i++){ char t; t=s[i]; s[i]=s[s.length-i-1]; s[s.length-i-1]=t; } } }
Solution:
- Separate from the middle, exchange the first and last characters, and recurs in turn.
- The time complexity is O(n), and the space complexity is O(1)
557. Reverse word III in string
Topics and examples
Given a string, you need to reverse the character order of each word in the string, while still retaining the initial order of spaces and words.
Example:
Enter: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Tips:
In a string, each word is separated by a single space, and there are no additional spaces in the string.
Code 1:
class Solution { public String reverseWords(String s) { String []str=s.split(" "); String afterReverse=""; for(int i=0;i<str.length;i++){ StringBuffer sb = new StringBuffer(str[i]); if(i!=str.length-1){ afterReverse+=sb.reverse().toString()+" "; }else{ afterReverse+=sb.reverse().toString(); } } return afterReverse; } }
Code 2:
class Solution { public String reverseWords(String s) { String []str=s.split(" "); StringBuffer sb = new StringBuffer(); StringBuffer sb1 = new StringBuffer(); for(int i=0;i<str.length;i++){ sb = new StringBuffer(str[i]); if(i!=str.length-1){ sb1.append(sb.reverse()); sb1.append(" "); }else{ sb1.append(sb.reverse()); } } return sb1.toString(); } }
Solution:
- Firstly, the string is divided into a string array with spaces; for loop, reverse, toString to string
- The difference between code 2 and code 1 is that the append method of StringBuffer is used to store the inverted string, which takes less time than adding strings.
- The time complexity is O(n), and the space complexity is O(n)
2022-1-14
876. Intermediate node of linked list
Topics and examples
Given a non empty single linked list with head node, return the intermediate node of the linked list.
If there are two intermediate nodes, the second intermediate node is returned.
Example 1:
Input: [1,2,3,4,5]
Output: node 3 in this list (serialized form: [3,4,5])
The returned node value is 3. (the serialization expression of this node in the evaluation system is [3,4,5]).
Note that we returned an object ans of ListNode type, as follows:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next next. next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: node 4 in this list (serialized form: [4,5,6])
Since the list has two intermediate nodes with values of 3 and 4, we return the second node.
Tip: the number of nodes in a given linked list is between 1 and 100.
code:
/** - Definition for singly-linked list. - public class ListNode { - int val; - ListNode next; - ListNode() {} - ListNode(int val) { this.val = val; } - ListNode(int val, ListNode next) { this.val = val; this.next = next; } - } */ class Solution { public ListNode middleNode(ListNode head) { ListNode slow=head,fast=head; while(fast!=null&&fast.next!=null){ slow=slow.next; fast=fast.next.next; } return slow; } }
Solution:
- Fast and slow pointer method, slow is the slow pointer, one step at a time; Fast is a fast pointer, two steps at a time.
- When fast comes to the end, slow just comes to the middle node
19. Delete the penultimate node of the linked list
Topics and examples
Give you a linked list, delete the penultimate node of the linked list, and return the head node of the linked list.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Tips:
The number of nodes in the linked list is sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
code:
/** - Definition for singly-linked list. - public class ListNode { - int val; - ListNode next; - ListNode() {} - ListNode(int val) { this.val = val; } - ListNode(int val, ListNode next) { this.val = val; this.next = next; } - } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy=new ListNode(0,head); ListNode first=head; ListNode second=dummy; for(int i=0;i<n;i++){ first=first.next; } while(first!=null){ first=first.next; second=second.next; } second.next=second.next.next; ListNode ans=dummy.next;//Head node return ans; } }
Solution:
- First points to the head pointer and second points to the dummy pointer (the dummy pointer points to the head pointer). If the two are separated by n, when first points to the end, the next node of second is the node to be deleted.
- Delete node: second refers to the next node of the deleted node (second.next=second.next.next;)
- The head node is the next node of the dummy node.
2022-1-17
3. Longest substring without repeated characters
Topics and examples
Given a string s, please find the length of the longest substring that does not contain duplicate characters.
Example 1:
Enter: s = "abcabcbb"
Output: 3
Explanation: because the longest substring without repeated characters is "abc", its length is 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: because the longest substring without repeated characters is "b", its length is 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: because the longest substring without repeated characters is "wke", its length is 3.
Please note that your answer must be the length of the substring, "pwke" is a substring, not a substring.
Example 4:
Input: s = ""
Output: 0
Tips:
0 <= s.length <= 5 * 104
s consists of English letters, numbers, symbols and spaces
code:
class Solution { public int lengthOfLongestSubstring(String s) { int n=s.length(); Set<Character> set=new HashSet<>(); int right=-1; int max=0; for(int left=0;left<n;left++){ if(left!=0){ set.remove(s.charAt(left-1)); } while(right+1<n&&!set.contains(s.charAt(right+1))) { set.add(s.charAt(right+1)); right++; } max=Math.max(max,right-left+1); } return max; } }
Solution:
- Pop up method, using hashset to store the characters in the string. When the first character is taken as the starting character, look at the length of the longest non repeating sub character, then look at the first character as the starting character, look at the length of the longest non repeating sub character, and repeat it in turn. Finally, take the length of the sub character with the maximum length.
- When there is no character in the set, add the character to the set and move the right pointer to the right. End the loop after encountering the same character.
- The next cycle is to move the left pointer to the right a, take out the character in front of the left pointer from the set, and continue to judge whether there are duplicate characters.
- The length of the substring is the right pointer minus the left pointer plus one.
- Delete the method of set: remove(), add()
- Time complexity: O(N), where N is the length of the string. The left and right pointers traverse the entire string once, respectively.
- Space complexity: O(∣) Σ ∣), where Σ Represents the character set (that is, the characters that can appear in the string), ∣ Σ ∣ indicates the size of the character set. The character set is not specified in this question, so it can default to all characters with ASCII code within [0, 128), i.e. ∣ Σ ∣=128. We need to use a hash set to store the characters that have appeared, and the maximum number of characters is ∣ Σ ∣ so the space complexity is O(∣) Σ ∣).
567. Arrangement of strings
and Sword finger Offer II 014 Anagrams in strings equally
Topics and examples
Give you two strings s1 and s2 and write a function to judge whether s2 contains the arrangement of s1. If yes, return true; Otherwise, false is returned.
In other words, one of the permutations of s1 is a substring of s2.
Example 1:
Input: s1 = "ab" s2 = "eidbaooo"
Output: true
Explanation: s2 contains one of the permutations of s1 ("ba")
Example 2:
Input: s1 = "ab" s2 = "eidboaoo"
Output: false
Tips:
1 <= s1.length, s2.length <= 104
s1 and s2 contain only lowercase letters
code:
class Solution { public boolean checkInclusion(String s1, String s2) { int n=s1.length(); int m=s2.length(); if(n>m){ return false; } int []cnt1=new int[26]; int []cnt2=new int[26]; for(int i=0;i<n;i++){ ++cnt1[s1.charAt(i)-'a']; ++cnt2[s2.charAt(i)-'a']; } if(Arrays.equals(cnt1,cnt2)){ return true; } for(int i=n;i<m;i++){ ++cnt2[s2.charAt(i)-'a']; --cnt2[s2.charAt(i-n)-'a']; if(Arrays.equals(cnt1,cnt2)){ return true; } } return false; } }
Solution:
- In the pop-up window method, only the substring with the same length of s2 and s1 can be one of the permutations of s1. So the pop-up window length is the length n of s1.
- Two int arrays are set to record the number of occurrences of s1 and s2 characters. If s1 is the same and is a substring in s2, the two arrays are equal.
- Each pop-up window moves n characters to the right. If they are equal, it is true; false if not equal
- Time complexity: O(n+m + ∣ Σ ∣), where n is the length of string s1 and M is the length of string s2, Σ Is the character set. The character set in this question is lowercase letters, ∣ Σ ∣=26.
- Space complexity: O(∣) Σ ∣).
2022-1-18
733. Image rendering
Topics and examples
There is a picture represented by a two-dimensional integer array. Each integer represents the pixel value of the picture, and the value is between 0 and 65535.
Give you a coordinate (sr, sc) to represent the pixel value (row, column) at the beginning of image rendering and a new color value newColor, so that you can color the image again.
In order to complete the coloring work, starting from the initial coordinates, record the connected pixels with the same pixel value as the initial coordinates in the upper, lower, left and right directions of the initial coordinates, and then record the qualified pixels in these four directions and their corresponding connected pixels with the same pixel value as the initial coordinates in the four directions,... Repeat the process. Change the color value of all recorded pixels to the new color value.
Finally, the color rendered image is returned.
Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2], [2,2,0], [2,0,1]]
Resolution:
In the middle of the image, (coordinates (sr,sc)=(1,1)),
The color of all eligible pixels on the path is changed to 2.
Note that the pixel in the lower right corner is not changed to 2,
Because it is not a pixel connected with the initial point in the up, down, left and right directions.
be careful:
The length of image and image[0] is in the range [1, 50].
The given initial point will satisfy 0 < = SR < image Length and 0 < = SC < image [0] length.
The color values represented by image[i][j] and newColor are in the range [0, 65535].
code:
class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int currColor=image[sr][sc]; if(currColor!=newColor){ dfs(image,sr,sc,currColor,newColor); } return image; } public void dfs(int [][]image,int x,int y,int currColor,int newColor){ int []dx={1,0,0,-1}; int []dy={0,1,-1,0};//Up, right, left, down if(image[x][y]==currColor){ image[x][y]=newColor; for(int i=0;i<4;i++){ int mx=x+dx[i]; int my=y+dy[i]; if(mx>=0&&mx<image.length &&my>=0&&my<image[0].length){ dfs(image,mx,my,currColor,newColor); } } } } }
Solution:
- Depth search dfs, which uses recursion (stack). dx and dy arrays are used to store the changes of row and column subscripts at the top, right, left and bottom.
- If the color value at the corresponding coordinate is equal to the current value, the color value at the corresponding coordinate is equal to the new color value.
- Then check whether the subscript values of the upper right and lower left exceed the boundary. If they do not exceed the boundary, conduct a depth search.
- Time complexity: O(n) × m) Where N and m are the number of rows and columns of the two-dimensional array, respectively. In the worst case, you need to traverse all the squares once.
- Space complexity: O(n) × m) Where N and m are the number of rows and columns of the two-dimensional array, respectively. Mainly the overhead of stack space.
695. Maximum area of the island
Topics and examples
Give you a binary matrix grid of size m x n.
Islands are a combination of adjacent ones (representing land). The "adjacent" here requires that two ones must be adjacent in four horizontal or vertical directions. You can assume that all four edges of the grid are surrounded by 0 (representing water).
The area of an island is the number of cells on the island with a value of 1.
Calculate and return the largest island area in the grid. If there are no islands, the return area is 0.
Example 1:
For a grid, it is an input for a grid = [[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,, 1,1,0,0,0], [0,0,0,0,0,0,1,0,0,0,0,0]
Output: 6
Explanation: the answer should not be 11, because the island can only contain 1 in the horizontal or vertical directions.
Example 2:
Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0
Tips:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j] is 0 or 1
code:
class Solution { public int maxAreaOfIsland(int[][] grid) { int ans=0; int n=grid.length; int m=grid[0].length; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ ans=Math.max(ans,dfs(grid,i,j)); } } return ans; } public int dfs(int [][]grid,int x,int y){ if(x<0||x==grid.length||y<0|| y==grid[0].length||grid[x][y]==0){ return 0; } grid[x][y]=0; int []di={1,0,0,-1}; int []dj={0,1,-1,0};//Up, right, left, down int ans=1; for(int k=0;k<4;k++){ int mi=x+di[k]; int mj=y+dj[k]; ans+=dfs(grid,mi,mj); } return ans; } }
Solution:
- Depth first search dfs. There are multiple islands, and the largest island is required.
- In the dfs function, if the subscript is out of bounds or the corresponding value is 0, the island area is 0. In order to prevent double counting of islands, the value of traversed islands is changed to 0.
- Find the island area and see whether the value of the upper, lower, left and right is 1, that is, pass in the upper, lower, left and right subscripts, and conduct a deep search again.
- n is the number of rows of the array, m is the number of columns of the array, the time complexity is O(mn), and the space complexity is O(mn).
2022-1-19
617. Merge binary tree
Topics and examples
Given two binary trees, imagine that when you overlay one of them on the other, some nodes of the two binary trees will overlap.
You need to merge them into a new binary tree. The merging rule is that if two nodes overlap, their values will be added as the new value after node merging. Otherwise, the node that is not NULL will be directly used as the node of the new binary tree.
Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/
4 5
/ \ \
5 4 7
Note: the merge must start at the root node of both trees.
code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { if(root1==null){ return root2; } if(root2==null){ return root1; } TreeNode t=new TreeNode(root1.val+root2.val); t.left=mergeTrees(root1.left,root2.left); t.right=mergeTrees(root1.right,root2.right); return t; } }
Solution:
- Deep search: if one subtree is null, another subtree will be returned. The left subtree performs depth search, and the right subtree performs depth search. If the corresponding positions of two subtrees are null, null is returned; If one subtree is null and the other has a value, the value is returned. If both have values, the two numbers are added.
- Time complexity: O(min(m,n)), where m and N are the number of nodes of two binary trees respectively. Carry out breadth first search on two binary trees at the same time. Only when the corresponding nodes in the two binary trees are not empty can the node be accessed. Therefore, the number of nodes accessed will not exceed the number of nodes of the smaller binary tree.
- Spatial complexity: O(min(m,n)), where m and N are the number of nodes of two binary trees respectively. The spatial complexity depends on the number of elements in the queue. The number of elements in the queue will not exceed the number of nodes of the smaller binary tree.
116. Fill in the next right node pointer of each node
Topics and examples
Given a perfect binary tree, all leaf nodes are in the same layer, and each parent node has two child nodes. Binary tree is defined as follows:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Fill in each of its next pointers so that this pointer points to its next right node. If the next right node cannot be found, set the next pointer to NULL.
In the initial state, all next pointers are set to NULL.
Advanced:
You can only use constant level extra space.
Using recursion to solve the problem also meets the requirements. The stack space occupied by the recursive program in this problem is not considered as additional space complexity.
Example:
Input: root = [1,2,3,4,5,6,7]
Output: [1, #, 2,3, #, 4,5,6,7, #]
Explanation: given A binary tree, as shown in figure A, your function should fill in each next pointer to point to its next right node, as shown in Figure B. The serialized output is arranged by sequence traversal, and the nodes of the same layer are connected by the next pointer,'# 'marks the end of each layer.
Tips:
The number of nodes in the tree is less than 4096
-1000 <= node.val <= 1000
code:
/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } }; */ class Solution { public Node connect(Node root) { if (root == null) { return null; } connect(root.left, root.right); return root; } public void connect(Node left, Node right) { if (left != null && right != null) { left.next = right; connect(left.left, left.right); connect(left.right, right.left); connect(right.left, right.right); } } }
- Traverse the binary tree hierarchically, that is, the left of a layer and the next is the right of the same layer, that is, left Next = right. When connecting the next layer, it is the left node of the left subtree, the right node of the left subtree, the left node of the right subtree and the right node of the right subtree.
- N is the number of nodes of binary number. The time complexity is O(n) and the space complexity is O(1)
2022-1-20
542.01 matrix
Given a matrix mat composed of 0 and 1, please output a matrix of the same size, where each lattice is the distance from the corresponding position element in mat to the nearest 0.
The distance between two adjacent elements is 1.
Example 1:
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0], [0,1,0], [0,0,0]]
Example 2:
Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0], [0,1,0], [1,2,1]]
Tips:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j] is either 0 or 1.
At least one 0 in mat
code:
class Solution { static int [][]dir={{-1,0},{1,0},{0,-1},{0,1}}; public int[][] updateMatrix(int[][] mat) { int n=mat.length; int m=mat[0].length; int [][]dist=new int[n][m]; Queue<int[]> q=new LinkedList<int[]>(); boolean [][] b=new boolean[n][m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(mat[i][j]==0){ q.offer(new int[]{i,j});//Enter the queue b[i][j]=true; } } } //Breadth first search while(!q.isEmpty()){ int []cell=q.poll();//Out of queue int i=cell[0],j=cell[1]; for(int d=0;d<4;d++){ int ni=i+dir[d][0]; int nj=j+dir[d][1]; if(ni>=0&&ni<n&&nj>=0&&nj<m&&!b[ni][nj]){ dist[ni][nj]=dist[i][j]+1; q.offer(new int[]{ni,nj}); b[ni][nj]=true; } } } return dist; } }
Solution:
- Add the subscripts I and J that are zero in the matrix to the queue. If the queue is not empty, it will spread from zero to top, bottom, left and right, and the value will be increased by one for each diffusion step. Add the diffused subscripts to the queue in turn. Set the traversed flag array to true.
- The number of rows of the matrix is n, the number of columns is m, the time complexity is O(nm), and the space complexity is O(nm).
994. Rotten oranges
Topics and examples
In a given grid, each cell can have one of the following three values:
A value of 0 represents an empty cell;
A value of 1 represents fresh oranges;
A value of 2 represents rotten oranges.
Every minute, any fresh orange adjacent to the rotten orange (in four positive directions) will rot.
Returns the minimum number of minutes that must elapse until there are no fresh oranges in the cell. If this is not possible, return - 1.
Example 1:
Input: [[2,1,1], [1,1,0], [0,1,1]]
Output: 4
Example 2:
Input: [[2,1,1], [0,1,1], [1,0,1]]
Output: - 1
Explanation: the orange in the lower left corner (row 2, column 0) will never rot, because rot will only occur in four positive directions.
Example 3:
Input: [[0,2]]
Output: 0
Explanation: because there are no fresh oranges in 0 minutes, the answer is 0.
Tips:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j] is only 0, 1 or 2
code:
class Solution { //Get a two-dimensional array of elements from the bottom, top, left and right static int [][]dir={{-1,0},{1,0},{0,-1},{0,1}}; public int orangesRotting(int[][] grid) { int n=grid.length; int m=grid[0].length; int total=0; Queue<Integer> q=new LinkedList<Integer>(); Map<Integer,Integer> depth=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(grid[i][j]==2){ //Convert to one-dimensional array with unique index int code=i*m+j; q.offer(code);//Store rotten oranges //Store the time when the sentence becomes rotten, and key is the subscript of the array of sentences, //value is the decay time, and the initial time is 0. depth.put(code,0); } } } //Breadth first search while(!q.isEmpty()){ int code=q.poll();//Out of queue int i=code/m,j=code%m; for(int d=0;d<4;d++){ int ni=i+dir[d][0]; int nj=j+dir[d][1]; if(ni>=0&&ni<n&&nj>=0&&nj<m&&grid[ni][nj]==1){ grid[ni][nj]=2; int ncode=ni*m+nj; q.offer(ncode); //The key to counting is that the decay time of the upper, lower, left and right elements of the grid[i][j] should be the same depth.put(ncode,depth.get(code)+1); total=depth.get(ncode); } } } //If any element is 1, it means there are fresh oranges, and - 1 is returned for(int []row:grid){ for(int v:row){ if(v==1){ return -1; } } } return total; } }
Solution:
- and 542.01 matrix Similarly, breadth first search uses a map to record the time of rotten oranges. In one round of corrosion, the decay time of the upper, lower, left and right elements of the element grid[i][j] should be the same, and one should be added to the time of the previous round.
- The number of rows of the matrix is n, the number of columns is m, the time complexity is O(mn), and the space complexity is O(mn).
20222-1-21
77. Portfolio
Topics and examples
Given two integers n and k, returns the combination of all possible k numbers in the range [1, n].
You can return answers in any order.
Example 1:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Example 2:
Input: n = 1, k = 1
Output: [[1]]
Tips:
1 <= n <= 20
1 <= k <= n
code:
class Solution { List<List<Integer>> list =new ArrayList<List<Integer>>(); List<Integer> li=new ArrayList<Integer>(); public List<List<Integer>> combine(int n, int k) { dfs(1,n,k); return list; } public void dfs(int cur,int n,int k){ //The length of the temporary array li is added to the length of [cur,n]. If it is less than k, the array is empty. if(li.size()+n-cur+1<k){ return; } //If the length of the temporary array li is k, it will be added to the answer array list if(li.size()==k){ list.add(new ArrayList<Integer>(li)); return; } //If the current position is selected, add cur to the li array li.add(cur); dfs(cur+1,n,k); //If you do not select the current location li.remove(li.size()-1); dfs(cur+1,n,k); } }
Solution:
- Recursive implementation of combinatorial enumeration
- The time complexity is O ((n k) * k), and the space complexity is O (n+k) = O(n)
46. Full arrangement
Topics and examples
Given an array nums without duplicate numbers, all possible permutations are returned. You can return answers in any order.
Example 1:
Input: num = [1,2,3]
Output: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
Example 2:
Input: num = [0,1]
Output: [[0,1], [1,0]]
Example 3:
Input: num = [1]
Output: [[1]]
Tips:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
All integers in nums are different from each other
code:
class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> ans=new ArrayList<List<Integer>>(); List<Integer> output=new ArrayList<Integer>(); for(int num:nums){ output.add(num); } int n=nums.length; backtrack(n,output,ans,0); return ans; } public void backtrack(int n,List<Integer> output, List<List<Integer>> ans,int first){ if(first==n){ ans.add(new ArrayList<Integer>(output)); } for(int i=first;i<n;i++){ //Dynamic maintenance array Collections.swap(output,first,i); //Continue to fill in the next number recursively backtrack(n,output,ans,first+1); //Undo operation Collections.swap(output,first,i); } } }
Solution:
- Backtracking method: define the backtrack (first,output) function, fill in the first position, and the current arrangement is output
- When first==n, it means that it has been filled in. Put output into the answer array and the recursion ends.
- When first < n, think about which number should be put, and then continue to call the function backtrack (first+1,output). When backtracking, undo the number of this position and continue to try.
- How to judge whether a number is added, you can use the tag array or another method. Divide the array into two parts. The left is the number added to the arrangement, and the right is the number added. If you want to add a number, exchange the current subscript number and the number to be added
- N is the length of the sequence, and the time complexity is O(n) × n!), The space complexity is O(n).
2022-1-22
70. Climb stairs
198. House raiding
It is the same as the problem of dynamic programming
120. Triangle minimum path and
Topics and examples
Given a triangle, find the minimum path sum from top to bottom.
Each node can only move to the next step in the adjacent row. Adjacent nodes here refer to two nodes whose subscript is the same as or equal to the subscript + 1 of the previous node. That is, if it is in the subscript i of the current row, the next step can be moved to the subscript i or i + 1 of the next row.
Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: as shown in the following diagram:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Example 2:
Input: triangle = [[-10]]
Output: - 10
Tips:
1 <= triangle.length <= 200
triangle[0].length == 1
triangle[i].length == triangle[i - 1].length + 1
-104 <= triangle[i][j] <= 104
code:
class Solution { public int minimumTotal(List<List<Integer>> triangle) { int n=triangle.size(); int [][]a=new int[n][n]; a[0][0]=triangle.get(0).get(0); for(int i=1;i<n;i++){ a[i][0]=a[i-1][0]+triangle.get(i).get(0); for(int j=1;j<i;j++){ a[i][j]=Math.min(a[i-1][j-1],a[i-1][j])+triangle.get(i).get(j); } a[i][i]=a[i-1][i-1]+triangle.get(i).get(i); } int min=a[n-1][0]; for(int k=1;k<n;k++){ min=Math.min(min,a[n-1][k]); } return min; } }
Solution:
- Set the shortest path of an array stored in line I and line J. if it is in the subscript i of the current line, the next step can be moved to the subscript i or i + 1 of the next line. So you can get a [i] [J] = math min(a[i-1][j],a[i-1][j-1])+triangle. get(i). get(j)
- There are i+1 elements in line i, and their corresponding range of j is [0,i].
- Look at the boundary: when j is equal to 1, that is, a [i] [0] = a [I-1] [0] + triangle get(i). Get (0), no a[i-1][j-1]
- When j is equal to I, a [i] [i] = a [I-1] [I-1] + triangle get(i). Get (I), the last element of each line can only be reached by the last element of the previous line.
- Finally, find the minimum value of all numbers in the last line, that is, the minimum value of the path ending with the last line.
- The time complexity is O (n2), and the space complexity is (n2)
2. Basic Edition
2022-2-7
34. Find the first and last position of an element in a sorted array
Topics and examples
Given an integer array nums arranged in ascending order and a target value target. Find the start and end positions of the given target value in the array.
If the target value target does not exist in the array, return [- 1, - 1].
Advanced:
Can you design and implement an algorithm with time complexity of O(log n) to solve this problem?
Example 1:
Input: num = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: num = [5,7,7,8,8,10], target = 6
Output: [- 1, - 1]
Example 3:
Input: num = [], target = 0
Output: [- 1, - 1]
Tips:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums is a non decreasing group
-109 <= target <= 109
code:
class Solution { public int[] searchRange(int[] nums, int target) { int leftIndex=binarySearch(nums,target,true); int rightIndex=binarySearch(nums,target,false)-1; System.out.println(leftIndex+" "+rightIndex); if(leftIndex<=rightIndex&&rightIndex<nums.length&&nums[leftIndex]==target&&nums[rightIndex]==target){ return new int[]{leftIndex,rightIndex}; } return new int[]{-1,-1}; } public int binarySearch(int []nums,int target,boolean flag){ int left=0; int right=nums.length-1; int ans=nums.length; while(left<=right){ int mid=(left+right)/2; if(nums[mid]>target||(nums[mid]>=target&&flag)){ right=mid-1; ans=mid; }else{ left=mid+1; } } return ans; } }
Solution:
- Binary search: finding leftindexes is the first subscript greater than or equal to target in the array. Finding the first subscript greater than target in the array can distinguish the two cases with a Boolean value.
- Then verify whether the left and right subscripts meet the conditions
- The time complexity is O (log n), and the space complexity is O(1)
2022-2-16
153. Find the minimum value in the rotation sort array
Topics and examples
An array with a length of n is known, which is arranged in ascending order in advance. After 1 to n rotations, the input array is obtained. For example, the original array nums = [0,1,2,4,5,6,7] may get after changing:
If you rotate 4 times, you can get [4,5,6,7,0,1,2]
If you rotate 7 times, you can get [0,1,2,4,5,6,7]
Note that the array [a[0], a[1], a[2],..., a[n-1]] rotates once and the result is array [a[n-1], a[0], a[1], a[2],..., a[n-2]].
Give you an array nums with different element values. It was originally an array arranged in ascending order and rotated many times according to the above situation. Please find and return the smallest element in the array.
Example 1:
Input: num = [3,4,5,1,2]
Output: 1
Explanation: the original array is [1,2,3,4,5]. Rotate it for 3 times to get the input array.
Example 2:
Input: num = [4,5,6,7,0,1,2]
Output: 0
Explanation: the original array is [0,1,2,4,5,6,7]. Rotate it for 4 times to get the input array.
Example 3:
Input: num = [11,13,15,17]
Output: 11
Explanation: the original array is [11,13,15,17]. Rotate it for 4 times to get the input array.
Tips:
n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
All integers in nums are different from each other
Num was originally an array sorted in ascending order and rotated 1 to n times
code:
class Solution { public int findMin(int[] nums) { //The first method // Arrays.sort(nums); // return nums[0]; //The second method int ans=nums[0]; for(int i=0;i<nums.length-1;i++){ if(nums[i]>nums[i+1]){ ans=nums[i+1]; break; } } return ans; } }
Solution:
- The last number in reverse order is the minimum value. If there is no reverse order, the minimum value is the first number.
- The time complexity is O (n), and the space complexity is O(1)
2, Sword finger offer
2022-1-11
Sword finger Offer II 001 Integer division
Topics and examples
Given two integers a and B, find the quotient a/b of their division. It is required that the multiplication sign '*', division sign '/' and remainder sign '%' shall not be used.
be careful:
The result of integer division should truncate its decimal part, such as truncate(8.345) = 8 and truncate(-2.7335) = -2
Suppose that our environment can only store 32-bit signed integers, and its numerical range is [− 231, 231 − 1]. In this question, if the division result overflows, 231 − 1 is returned
Example 1:
Input: a = 15, b = 2
Output: 7
Explanation: 15/2 = truncate(7.5) = 7
Example 2:
Input: a = 7, b = -3
Output: - 2
Explanation: 7/-3 = truncate(-2.33333...) = - 2
Example 3:
Input: a = 0, b = 1
Output: 0
Tips:
-231 <= a, b <= 231 - 1
b != 0
code
class Solution { public int divide(int a, int b) { int count=0; boolean flag=false; if(b==0){ return 0; } if(a==Integer.MIN_VALUE){ if(b==1){ return Integer.MIN_VALUE; } if(b==-1){ return Integer.MAX_VALUE; } } if(b==Integer.MIN_VALUE){ if(a==Integer.MIN_VALUE){ return 1; }else{ return 0; } } if((a>0&&b<0)||(a<0&&b>0)){ flag=true; } //Prevent digital overflow if(a>0){ a=-a; } if(b>0){ b=-b; } while(a<=b){ a-=b; count++; } if(flag){ count=-count; } return count; } }
Problem solution
- Using subtraction instead of multiplication, the most important thing is to consider the special case integer MIN_ VALUE,Integer.MAX_VALUE and 0.
- Set whether the flag ID needs to change the symbol. When the divisor and the dividend symbol are different, flag=true, the result is reversed, otherwise it remains unchanged.
- The time complexity is O (n), and the space complexity is O(1)
Sword finger Offer II 002 Binary addition
Topics and examples
Given two 01 strings a and b, please calculate their sum and output them as binary strings.
The input is a non empty string and contains only the numbers 1 and 0.
Example 1:
Input: a = "11", b = "10"
Output: "101"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Tips:
Each string consists only of the characters' 0 'or' 1 '.
1 <= a.length, b.length <= 10^4
If the string is not "0", it does not contain leading zeros.
code:
class Solution { public String addBinary(String a, String b) { return Integer.toBinaryString( Integer.parseInt(a,2)+Integer.parseInt(b,2) ); } }
Solution:
- Convert binary to decimal, and then return to binary string
- Integer. ParseInt (String s, int radius) is to find the decimal number of "int radius" binary number "String s".
- redix stands for hexadecimal, s stands for binary string, and integer ParseInt (a, 2) represents the decimal number of binary number a
- Integer. The tobinarystring () method converts a number of type int into binary and then outputs it as a string
- If the number of bits of a is n and the number of bits of b is m, the asymptotic time complexity of this algorithm is O(n+m).
- Space complexity is O(1)
Sword finger Offer II 003 The number of 1 in the first n binary digits
Topics and examples
Given a non negative integer n, calculate the number of 1 in the binary representation of each number between 0 and N and output an array.
Example 1:
Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
Example 2:
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
explain:
0 <= n <= 10^5
code:
class Solution { public int[] countBits(int n) { int []a=new int[n+1]; for(int i=0;i<=n;i++){ int j=i; while(j!=0){ if(j%2==1){ a[i]++; } j=j/2; } } return a; } }
Problem solution
- The number of binary 1 is the number of times that the remainder of 2 is equal to 1
- The time complexity is O(n), and the space complexity is O(n)
2022-1-12
Sword finger Offer II 004 A number that appears only once
Topics and examples
Give you an integer array nums. Except that an element appears only once, each other element appears exactly three times. Please find and return the element that appears only once.
Example 1:
Input: num = [2,2,3,2]
Output: 3
Example 2:
Input: num = [0,1,0,1,0,1100]
Output: 100
Tips:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
In nums, each element appears exactly three times except that one element appears only once
Code (hash table method):
class Solution { public int singleNumber(int[] nums) { Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int num:nums){ map.put(num,map.getOrDefault(num,0)+1); } int ans=0; for(Map.Entry<Integer,Integer> entry:map.entrySet()){ int num=entry.getKey(); int occ=entry.getValue(); if(occ==1){ ans=num; break; } } return ans; } }
Solution:
- Map.getOrDefault(Object key, V defaultValue); If there is a key in the map, the value corresponding to the key is returned. If the key does not exist in the map, the default value is returned. If the value of key is the same, add one to the value.
- map.put(num, map.getOrDefault(num, 0) + 1); Indicates: if there is a key, the value corresponding to num will be increased by 1 after each operation. If there is no key, the default value of 0 will be returned.
- Map.Entry is an internal interface declared by map. This interface is generic and is defined as entry < K, V >. It represents a key value in the map.
- map. The return value of entryset() is a Set set. The type of this Set is map Entry.
- Map. The entry contains getKey() and getValue () methods. getKey() gets the key, which is the value of the array; getValue() gets the value, which is the number of occurrences.
- Time complexity: O(n), where n is the length of the array.
- Space complexity: O(n). The hash map contains at most ⌊ n/3 ⌋ + 1 elements, that is, the required space is O(n).
Sword finger Offer II 005 Maximum product of word length
Topics and examples
Given a string array words, please calculate the maximum value of the product of the two strings words[i] and words[j] when they do not contain the same characters. Suppose that the string contains only lowercase letters of English. Returns 0 if there is no pair of strings that do not contain the same characters.
Example 1:
Input: words = ["abcw", "baz", "foo", "bar", "fxyz", "abcdef"]
Output: 16
Explanation: these two words are "abcw" and "fxyz". They do not contain the same characters, and the product of length is the largest.
Example 2:
Input: words = ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Output: 4
Explanation: these two words are "ab" and "cd"
Example 3:
Input: words = ["a", "aa", "aaa", "aaaa"]
Output: 0
Explanation: there are no such two words.
Tips:
2 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i] contains only lowercase letters
code:
class Solution { public int maxProduct(String[] words) { int n=words.length; int []arr=new int[n]; for(int i=0;i<n;i++){ int a=0; for(int j=0;j<words[i].length();j++){ a|=(1<<(words[i].charAt(j)-'a')); } arr[i]=a; } int max=0; for(int i=0;i<n-1;i++){ for(int j=i+1;j<n;j++){ if((arr[i]&arr[j])==0){ max=Math.max(max,words[i].length()*words[j].length()); } } } return max; } }
Solution:
- Convert each string in the words array into a binary number and store it in the int array. For example, if it is a, the first digit is 1, and if it is b, the first digit is 1.
- words[i].charAt(j) - 'a') is to judge how many bits to move to the left. Then set the specified position to 1, that is, 1 < < (words[i].charAt(j) - 'a'), and 0 or to obtain the binary number of the string.
- If the sum of the binary numbers of the two strings is 0, it means that the two strings do not have the same string. The maximum product is the product of the previous maximum product and the length of the two strings.
- The time complexity is O (n), and the space complexity is O (n)
Sword finger Offer II 006 Sort the sum of two numbers in the array
Topics and examples
Given an integer array numbers arranged in ascending order, please find two numbers from the array. The sum of the two numbers is equal to the target number target.
The function should return the subscript values of these two numbers as an array of integers with length 2. The subscript of numbers starts counting from 0, so the answer array should meet 0 < = answer [0] < answer [1] < numbers length .
Suppose that there is only one pair of qualified numbers in the array, and a number cannot be used twice.
Example 1:
Input: numbers = [1,2,4,6,10], target = 8
Output: [1,3]
Explanation: the sum of 2 and 6 is equal to the target number of 8. So index1 = 1, index2 = 3
Example 2:
Input: numbers = [2,3,4], target = 6
Output: [0,2]
Example 3:
Input: numbers = [-1,0], target = -1
Output: [0,1]
code:
class Solution { public int[] twoSum(int[] numbers, int target) { int []a=new int[2]; int left=0; int right=numbers.length-1; if(numbers==null||numbers.length<=0){ return a; } while(left<right){ if(numbers[left]+numbers[right]>target){ right--; }else if(numbers[left]+numbers[right]<target){ left++; }else if(numbers[left]+numbers[right]==target){ a[0]=left; a[1]=right; break; } } return a; } }
Problem solution
- Double finger needling, left = 0, right = num Length, if the addition is greater than the target value, the right pointer moves to the left; If the addition is less than the target value, the left pointer moves to the right
- Traversing the array, the time complexity is O(n);
- An auxiliary array is used, and the space complexity is O (n)
2022-1-13
Sword finger Offer II 007 Three numbers with zero in the array
Topics and examples
Given an array num containing n integers, judge whether there are three elements a, b and c in num, so that a + b + c = 0? Please find all triples with a sum of 0 and no duplicates.
Example 1:
Input: num = [- 1,0,1,2, - 1, - 4]
Output: [- 1, - 1,2], [- 1,0,1]]
Example 2:
Input: num = []
Output: []
Example 3:
Input: num = [0]
Output: []
Tips:
0 <= nums.length <= 3000
-10^5 <= nums[i] <= 10^5
code:
class Solution { public List<List<Integer>> threeSum(int[] nums) { int n=nums.length; if(nums==null||n<3){ return new ArrayList<>(); } List<List<Integer>> list=new ArrayList<>(); Arrays.sort(nums); for(int i=0;i<n-2;i++){ if(i>0&&nums[i]==nums[i-1]) continue; int target=-nums[i]; int left=i+1; int right=n-1; while(left<right){ if(nums[left]+nums[right]==target){ list.add(Arrays.asList(nums[i],nums[left],nums[right])); //duplicate removal while(left<right&&nums[left]==nums[++left]);//If the two numbers are equal, enter the cycle and the following steps cannot be carried out; If not, continue with the following steps while(left<right&&nums[right]==nums[--right]); }else if(nums[left]+nums[right]>target){ right--; }else{ left++; } } } return list; } }
Solution:
- Double finger needling method: sort first, then one pointer points to the next element of the current element, and the other points to the last element. The target value is the current element.
- If the sum of the target value and the elements of the double pointer is equal, the three values are added to the array, and the front pointer moves backward and the rear pointer moves forward; If the target value is greater than the sum of the elements of the double pointer, the front pointer moves back; If the target value is less than the sum of the elements of the double pointer, the back pointer moves forward;
- The time complexity is O (nlog2n),
- The space complexity is O (n2)
Sword finger Offer II 008 And the shortest subarray greater than or equal to target
Topics and examples
Given an array containing n positive integers and a positive integer target.
Find out the continuous sub array [numsl, numsl+1,..., numsr-1, numsr] with the smallest length satisfying its sum ≥ target in the array, and return its length. If there is no eligible subarray, 0 is returned.
Example 1:
Input: target = 7, Num = [2,3,1,2,4,3]
Output: 2
Explanation: subarray [4,3] is the subarray with the smallest length under this condition.
Example 2:
Input: target = 4, Num = [1,4,4]
Output: 1
Example 3:
Input: target = 11, Num = [1,1,1,1,1,1,1]
Output: 0
Tips:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105
Code 1: (prefix and)
class Solution { public int minSubArrayLen(int target, int[] nums) { int count=Integer.MAX_VALUE; int n=nums.length; if(n==0){ return 0; } int []sum=new int[n+1]; for(int i=1;i<n+1;i++){ sum[i]=sum[i-1]+nums[i-1]; } for(int i=1;i<n+1;i++){ int s=target+sum[i-1]; int bound=Arrays.binarySearch(sum,s); if(bound<0){ bound=-bound-1; } if(bound<=n){ count=Math.min(count,bound-(i-1)); } } return count==Integer.MAX_VALUE?0:count; } }
Problem solution 1:
- sum[i] is used to store the prefix and of nums[0] to nums[i-1].
- Binary search: find a subscript bound greater than or equal to i, so that sum [bound] - sum [i-1] > s (Arrays.binarySearch(sum,s);)
- Minimum length is bound-(i-1)
- The time complexity is O(nlog2n), and the space complexity is O(n)
Code 2 (pop-up method):
class Solution { public int minSubArrayLen(int target, int[] nums) { int left=0; int min=Integer.MAX_VALUE; int total=0; for(int right=0;right<nums.length;right++){ total+=nums[right]; while(left<=right&&total>=target){ total-=nums[left]; min=Math.min(min,right-left+1); left++; } } return min==Integer.MAX_VALUE?0:min; } }
Problem solution 2:
- If the prefix and total are greater than or equal to the target value, the minimum array length is the minimum value between the previous minimum length and right left + 1. Total subtracts the value pointed by left, and the pop-up window moves to the right.
- The time complexity is O(n), and the space complexity is O(1)
Sword finger Offer II 009 Subarray with product less than K
Given a positive integer array nums and integer k, please find out the number of consecutive sub arrays whose product is less than K in the array.
Example 1:
Input: num = [10,5,2,6], k = 100
Output: 8
Explanation: eight subarrays whose product is less than 100 are: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6].
It should be noted that [10,5,2] is not a subarray whose product is less than 100.
Example 2:
Input: num = [1,2,3], k = 0
Output: 0
Tips:
1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106
code:
class Solution { public int numSubarrayProductLessThanK(int[] nums, int k) { int left=0; int ret=0; int total=1; for(int right=0;right<nums.length;right++){ total*=nums[right]; while(left<=right&&total>=k){ total/=nums[left]; left++; } if(left<=right){ ret+=(right-left)+1; } } return ret; } }
Solution:
- Sliding window method, both left and right point to the head, and right adds itself.
- Then multiply the numbers between left and right. If total is greater than the target value, divide it by the value pointed to by left. If not, the number of subarrays generated is right left + 1
- The time complexity is O (n2) and the space complexity is O (1)
2022-1-14
Sword finger Offer II 010 Subarray with and k
Topics and examples
Given an array of integers and an integer k, please find the number of consecutive subarrays with K in the array.
Example 1:
Input: num = [1,1,1], k = 2
Output: 2
Explanation: this question [1,1] and [1,1] are two different situations
Example 2:
Input: num = [1,2,3], k = 3
Output: 2
Tips:
1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107
code:
class Solution { public int subarraySum(int[] nums, int k) { Map<Integer,Integer> map=new HashMap<>(); map.put(0,1); int sum=0;//Prefix and int count=0;//Record the number of subarrays for(int i=0;i<nums.length;i++){ sum+=nums[i]; count+=map.getOrDefault(sum-k,0); map.put(sum,map.getOrDefault(sum,0)+1); } return count; } }
Solution:
- I thought I could solve this problem with the pop-up method, but the pop-up method is applicable to positive integers. If there are negative numbers, I don't know whether to expand the right or shorten the left.
- Using map to store prefix and number of occurrences can avoid repetition.
- Use sum to temporarily store prefix and, map getOrDefault(sum-k,0); It depends on whether there is a sum-k value in the map. If so, it returns the value corresponding to the key value of sum-k. if not, it returns 0. Looking for sum-k is actually looking for the starting point of the sub array. Looking for K can only find those sub arrays whose starting position is 0.
- map.put(sum,map.getOrDefault(sum,0)+1); If there is sum in the map, add 1 to the value value corresponding to the original sum. If there is no sum in the map, set it to 1. Avoid duplication caused by the same prefix and.
- Traverse the array once, and the time complexity is O (n)
- map array is used, and the space complexity is O (n)
Sword finger offer II 011 0 and 1 have the same number of subarrays
Topics and examples
Given a binary array nums, find the longest continuous sub array containing the same number of 0 and 1, and return the length of the sub array.
Example 1:
Input: num = [0,1]
Output: 2
Description: [0, 1] is the longest continuous subarray with the same number of 0 and 1.
Example 2:
Input: num = [0,1,0]
Output: 2
Description: [0, 1] (or [1, 0]) is the longest continuous subarray with the same number of 0 and 1.
Tips:
1 <= nums.length <= 105
nums[i] either 0 or 1
code:
class Solution { public int findMaxLength(int[] nums) { Map<Integer,Integer> map=new HashMap<>(); int counter=0;//Prefix and int max=0; map.put(0,-1); for(int i=0;i<nums.length;i++){ if(nums[i]==1){ counter++; }else{ counter--; } if(map.containsKey(counter)){ int prevIndex=map.get(counter); max=Math.max(max,i-prevIndex); }else{ map.put(counter,i); } } return max; } }
Solution:
Prefix and + hash table method
- Counter temporarily stores the prefix and. When the element is 1, counter + +; When the element is 0, counter –
- Use a hash table to store the first occurrence of the subscript of the prefix and.
- If the value of counter already exists in the hash table, take out the corresponding subscript prevIndex of counter in the hash table. Num has the same number of 0 and 1 in the sub array from subscript prevIndex+1 to subscript i. the length of the sub array is i − prevIndex. Update the length of the longest continuous sub array with the length of the sub array;
- map.containsKey() determines whether a key value exists. If it exists, it is true; if it does not exist, it is false
- If the value of counter does not exist in the hash table, the key value pairs of current counter and current subscript i are stored in the hash table.
- The time complexity is O(n), and the space complexity is O(n)
Sword finger Offer II 012 The sum of the left and right subarrays is equal
Topics and examples
Give you an integer array nums, please calculate the central subscript of the array.
The central subscript of the array is a subscript of the array. The sum of all elements on the left is equal to the sum of all elements on the right.
If the central subscript is at the leftmost end of the array, the sum of the numbers on the left is regarded as 0 because there is no element to the left of the subscript. The same applies when the central subscript is at the rightmost end of the array.
If the array has multiple central subscripts, the one closest to the left should be returned. Returns - 1 if the array does not have a central subscript.
Example 1:
Input: num = [1,7,3,6,5,6]
Output: 3
Explanation:
The central subscript is 3.
Sum of left numbers = num [0] + num [1] + num [2] = 1 + 7 + 3 = 11,
Sum of right numbers = num [4] + num [5] = 5 + 6 = 11, the two are equal.
Example 2:
Input: num = [1, 2, 3]
Output: - 1
Explanation:
There is no central subscript in the array that meets this condition.
Example 3:
Input: num = [2, 1, - 1]
Output: 0
Explanation:
The central subscript is 0.
Sum of the numbers on the left side = 0, (there is no element on the left side of subscript 0),
Sum of right numbers = num [1] + num [2] = 1 + - 1 = 0.
Tips:
1 <= nums.length <= 104
-1000 <= nums[i] <= 1000
code:
class Solution { public int pivotIndex(int[] nums) { int n=nums.length; int total=0; int sum=0; for(int i=0;i<n;i++){ total+=nums[i]; } for(int i=0;i<n;i++){ if(2*sum+nums[i]==total){ return i; } sum+=nums[i]; } return -1; } }
Solution:
- The sum of all elements is total, the sum of left elements is sum, and the sum of right elements is total sum Numi
- If the left and right elements are equal, it means sum = total sum Numi, which means 2*sum+numi=total
- If 2*sum+numi=total, the subscript i of numi is returned
- If there is no middle subscript, - 1 is returned
- The time complexity is O(n), and the space complexity is O(1)
2022-1-17
Sword finger Offer II 013 Sum of two-dimensional submatrix
Topics and examples
Given a two-dimensional matrix, multiple requests of the following types:
Calculate the sum of the elements within its sub rectangle. The upper left corner of the sub matrix is (row1, col1) and the lower right corner is (row2, col2).
Implement NumMatrix class:
NumMatrix(int[][] matrix) initializes the given integer matrix
int sumRegion(int row1, int col1, int row2, int col2) returns the sum of the elements of the submatrix in the upper left corner (row1, col1) and the lower right corner (row2, col2).
Example 1:
Input:
["NumMatrix","sumRegion","sumRegion","sumRegion"]
[[[[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]],[2,1,4,3],[1,1,2,2],[1,2,2,4]]
Output:
[null, 8, 11, 12]
Explanation:
NumMatrix numMatrix = new NumMatrix([[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (sum of elements in the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (sum of elements in green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (sum of elements in the blue rectangle)
Tips:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
-105 <= matrix[i][j] <= 105
0 <= row1 <= row2 < m
0 <= col1 <= col2 < n
The sumRegion method can be called up to 104 times
code:
class NumMatrix { int [][]sum;//Prefix and public NumMatrix(int[][] matrix) { int n=matrix.length; if(n>0){ int m=matrix[0].length; sum=new int[n][m+1]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ sum[i][j+1]=sum[i][j]+matrix[i][j]; } } } } public int sumRegion(int row1, int col1, int row2, int col2) { int total=0; for(int i=row1;i<=row2;i++){ total+=sum[i][col2+1]-sum[i][col1]; } return total; } }
Solution:
- Line prefix and, for loops the prefix and sum of each line
- Behavior n, column m, time complexity O(mn)
- Behavior n, column m, spatial complexity O(mn)
2022-1-18
Sword finger Offer II 015 All modifiers in the string
Topics and examples
Given two strings S and p, find the substrings of all p's modifiers in S and return the starting indexes of these substrings. The order in which answers are output is not considered.
An anagram refers to a string of identical letters but arranged differently.
Example 1:
Input: s = "cbaebacd", p = "abc"
Output: [0,6]
Explanation:
The substring with the starting index equal to 0 is "cba", which is the modifier of "abc".
The substring with the starting index equal to 6 is "bac", which is the modifier of "abc".
Example 2:
Input: s = "abab", p = "ab"
Output: [0,1,2]
Explanation:
The substring with the starting index equal to 0 is "ab", which is the modifier of "ab".
The substring with the starting index equal to 1 is "ba", which is the modifier of "ab".
The substring with the starting index equal to 2 is "ab", which is the modifier of "ab".
Tips:
1 <= s.length, p.length <= 3 * 104
s and p contain only lowercase letters
code:
class Solution { public List<Integer> findAnagrams(String s, String p) { List<Integer> list=new ArrayList<>(); int []a=new int[26]; int []b=new int[26]; int n=p.length(); int m=s.length(); if(n>m){ return list; } for(int i=0;i<n;i++){ a[p.charAt(i)-'a']++; b[s.charAt(i)-'a']++; } if(Arrays.equals(a,b)){ list.add(0); } for(int i=n;i<m;i++){ b[s.charAt(i)-'a']++; b[s.charAt(i-n)-'a']--; if(Arrays.equals(a,b)){ list.add(i-n+1); } } return list; } }
Solution:
- And 567. Arrangement of strings and Sword finger Offer II 014 Anagrams in strings The same problem-solving ideas
- Only the return value changes from true\false to a variable array storing subscripts.
- The time complexity is O(n+m), and the space complexity is O(n+m)
Sword finger Offer II 016 Longest substring without duplicate characters
and 3. Longest substring without repeated characters equally
2022-1-20
Sword finger Offer II 018 Valid palindrome
Topics and examples
Given a string s, verify whether s is a palindrome string. Only alphabetic and numeric characters are considered, and the case of letters can be ignored.
In this question, the empty string is defined as a valid palindrome string.
Example 1:
Enter: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "Amana planacanalpanama" is a palindrome string
Example 2:
Enter: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome string
Tips:
1 <= s.length <= 2 * 105
The string s consists of ASCII characters
code:
class Solution { public boolean isPalindrome(String s) { boolean flag=true; List<Character> list=new ArrayList<>(); String str=s.toLowerCase(); for(int i=0;i<s.length();i++){ if((str.charAt(i)>='0'&&str.charAt(i)<='9')||(str.charAt(i)>='a'&&str.charAt(i)<='z')) { list.add(str.charAt(i)); } } for(int i = 0;i < list.size()/2; i ++){ if(list.get(i)!=list.get(list.size()-i-1)){ flag=false; break; } } return flag; } }
Solution:
- First, remove the interference of non numbers and letters, and convert uppercase letters into lowercase letters. Then convert the string into a character array. Because the number of characters is uncertain, List is used.
- Traversing the List, the first and last letters of the palindrome string are equal, and they are recursive in turn. If one is not equal, it is false, otherwise it is true.
- The string length is n, the variable character array length is m, the time complexity is O(m+n), and the space complexity is O(m)
2022-1-21
Sword finger Offer II 019 Delete at most one character to get a palindrome
Topics and examples
Given a non empty string s, please judge whether you can get a palindrome string if you delete at most one character from the string.
Example 1:
Input: s = "aba"
Output: true
Example 2:
Enter: s = "abca"
Output: true
Explanation: the "c" or "b" character can be deleted
Example 3:
Enter: s = "abc"
Output: false
Tips:
1 <= s.length <= 105
s consists of lowercase English letters
code:
class Solution { public boolean validPalindrome(String s) { for(int left=0,right=s.length()-1;left<right;left++,right--){ if(s.charAt(left)!=s.charAt(right)){ return hui(s,left+1,right)|| hui(s,left,right-1); } } return true; } //Judge whether the [left,right] of string s is palindrome public boolean hui(String s,int left,int right){ while(left<right){ if(s.charAt(left++)!=s.charAt(right--)){ return false; } } return true; } }
Solution:
- Another function is used to judge whether the [left,right] of string s is palindrome, compare the first letter with the last letter, and then recurs in turn. The difference between this and palindrome string is that there is a chance to remove characters, so it is also possible if the characters corresponding to left+1 and right are equal or the characters corresponding to left and Right-1 are equal.
- The time complexity is O(n2) and the space complexity is O(1)
2022-1-22
Sword finger Offer II 020 Number of palindrome substrings
Topics and examples
Given a string s, please calculate how many palindrome substrings there are in this string.
Substrings with different start or end positions, even if they are composed of the same characters, will be regarded as different substrings.
Example 1:
Enter: s = "abc"
Output: 3
Explanation: three palindrome substrings: "a", "b", "c"
Example 2:
Enter: s = "aaa"
Output: 6
Explanation: 6 palindrome substrings: "a", "a", "a", "aa", "aa", "aaa"
Tips:
1 <= s.length <= 1000
s consists of lowercase English letters
code:
class Solution { public int countSubstrings(String s) { int n=s.length(); int total=0; for(int i=0;i<n;i++){ int ans=0; int num=i+1; while(num<=n){ // System.out.println(s.substring(i,num)); // System.out.println(hui(s.substring(i,num))); if(hui(s.substring(i,num))){ ++ans; } num++; } total+=ans; } return total; } //Judge whether the string s is palindrome public boolean hui(String s){ StringBuffer sb = new StringBuffer(s); sb.reverse();//Method of inverting str String s1=new String(sb); if(s.equals(s1)){ return true; } return false; } }
Solution:
- One of the ways to judge the palindrome string: reverse the string. If the reversed string is the same as the string, it is the palindrome string, otherwise it is not the palindrome string. Note: equal () is used to compare equal strings, but = = is not used
- Then check whether the substring is a palindrome string. If it is a temporary increment, add one. Note: the temporary increment and the end subscript are set to 0 each time the for loop is used to facilitate the next count. The end subscript is equal to the actual subscript plus one.
- The time complexity is O(n2) and the space complexity is O(1)
2022-1-25
Sword finger Offer II 022 The entry node of the link in the linked list
Topics and examples
Given a linked list, return the first node from the linked list into the ring. Starting from the head node of the linked list, the first node entering the ring along the next pointer is the entry node of the ring. If the linked list is acyclic, null is returned.
In order to represent the rings in a given linked list, we use the integer pos to represent the position where the tail of the linked list is connected to the linked list (the index starts from 0). If pos is - 1, there is no ring in the linked list. Note that pos is only used to identify the ring and is not passed to the function as a parameter.
Note: it is not allowed to modify the given linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: returns the linked list node with index 1
Explanation: there is a ring in the linked list, and its tail is connected to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: returns the linked list node with index 0
Explanation: there is a ring in the linked list, and its tail is connected to the first node.
Example 3:
Input: head = [1], pos = -1
Output: return null
Explanation: there are no links in the linked list.
Tips:
The number of nodes in the linked list is within the range [0, 104]
-105 <= Node.val <= 105
The value of pos is - 1 or a valid index in the linked list
code:
/** - Definition for singly-linked list. - class ListNode { - int val; - ListNode next; - ListNode(int x) { - val = x; - next = null; - } - } */ public class Solution { public ListNode detectCycle(ListNode head) { Set<ListNode> set=new HashSet<>(); while(head!=null){ if(!set.add(head)){ return head; } head=head.next; } return head; } }
Solution:
- and 141. Circular linked list Almost, use set to store nodes. If there are duplicate nodes, it means that this node is the first node of the cycle.
- The time complexity is O(n), and the space complexity is O(n)
Sword finger Offer II 023 The first coincident node of two linked lists
Topics and examples
Given the head nodes headA and headB of two single linked lists, please find and return the starting node where the two single linked lists intersect. If the two linked lists have no intersection, null is returned.
As shown in the figure, two linked lists intersect at node c1:
The title data ensures that there are no links in the whole chain structure.
Note that after the function returns the result, the linked list must maintain its original structure.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
Output: Intersected at '8'
Explanation: the value of intersection node is 8 (note that if two linked lists intersect, it cannot be 0).
Starting from the respective header, linked list A is [4,1,8,4,5], and linked list B is [5,0,1,8,4,5].
In A, there are 2 nodes before the intersection node; In B, there are three nodes before the intersection node.
Example 2:
Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Intersected at '2'
Explanation: the value of intersection node is 2 (note that if two linked lists intersect, it cannot be 0).
Starting from the respective header, linked list A is [0,9,1,2,4], and linked list B is [3,2,4].
In A, there are 3 nodes before the intersection node; In B, there is one node before the intersection node.
Example 3:
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: null
Explanation: starting from the respective header, linked list A is [2,6,4], and linked list B is [1,5].
Because the two linked lists do not intersect, intersectVal must be 0, and skipA and skipB can be any value.
The two linked lists do not intersect, so null is returned.
Tips:
The number of nodes in listA is m
The number of nodes in listB is n
0 <= m, n <= 3 * 104
1 <= Node.val <= 105
0 <= skipA <= m
0 <= skipB <= n
If listA and listB have no intersection, intersectVal is 0
If listA and listB have an intersection, intersectVal == listA[skipA + 1] == listB[skipB + 1]
code:
/** - Definition for singly-linked list. - public class ListNode { - int val; - ListNode next; - ListNode(int x) { - val = x; - next = null; - } - } */ public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { Set<ListNode> set=new HashSet<>(); ListNode ans=new ListNode(); while(headA!=null){ set.add(headA); headA=headA.next; } while(headB!=null){ if(!set.add(headB)){ ans=headB; break; } headB=headB.next; } return ans.val==0?null:ans; } }
Solution:
- The time complexity is O(n), and the space complexity is O(n)
2022-1-26
Sword finger Offer II 024 Reverse linked list
Sword finger Offer II 025 Add two numbers in the linked list
Topics and examples
Two non empty linked lists l1 and l2 are given to represent two non negative integers. The highest digit is at the beginning of the linked list. Each of their nodes stores only one digit. Adding these two numbers will return a new linked list.
It can be assumed that neither number will start with zero except the number 0.
Example 1:
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Example 2:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
Example 3:
Input: l1 = [0], l2 = [0]
Output: [0]
Tips:
The length range of the linked list is [1, 100]
0 <= node.val <= 9
The input data ensures that the number represented by the linked list has no leading 0
Advanced: what if the input linked list cannot be modified? In other words, you cannot flip nodes in the list.
code:
/** - Definition for singly-linked list. - public class ListNode { - int val; - ListNode next; - ListNode() {} - ListNode(int val) { this.val = val; } - ListNode(int val, ListNode next) { this.val = val; this.next = next; } - } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { l1=reverse(l1); l2=reverse(l2); int d=0;//carry ListNode node=new ListNode(0),next=null; while(l1!=null||l2!=null||d!=0){ int a=l1==null?0:l1.val; int b=l2==null?0:l2.val; int sum=a+b+d; d=sum/10; node =new ListNode(sum%10,next); next=node;//Reverse linked list l1=l1==null?l1:l1.next; l2=l2==null?l2:l2.next; } return node; } public ListNode reverse(ListNode head){ ListNode prev=null; ListNode curr=head; while(curr!=null){ ListNode next=curr.next; curr.next=prev; prev=curr; curr=next; } return prev; } }
Solution:
- Reverse the linked list, add, set a variable as carry = the number corresponding to the two linked lists and add the carry to divide by 10, add the remaining number of 10 to the linked list, and then reverse the linked list
- The time complexity is O (n), max(n1,n2). n1 is the total number of elements in list 1 and n2 is the total number of elements in list 2
- Space complexity is O (n)
2022-1-27
Sword finger Offer II 027 Palindrome linked list
Topics and examples
Given the head node of a linked list, please judge whether it is a palindrome linked list.
If a linked list is a palindrome, the sequence of nodes in the linked list is the same from front to back and from back to front.
Example 1:
Input: head = [1,2,3,3,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Tips:
The length range of linked list L is [1, 105]
0 <= node.val <= 9
code:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public boolean isPalindrome(ListNode head) { ListNode head1=head; ListNode index=mid(head); ListNode head2=reverse(index.next); boolean flag=true; while(flag&&head2!=null){ if(head1.val!=head2.val){ flag=false; } head1=head1.next; head2=head2.next; } return flag; } //Find the center of the linked list public ListNode mid(ListNode head){ ListNode slow=head; ListNode fast=head; while(fast.next!=null&&fast.next.next!= null){ fast=fast.next.next; slow=slow.next; } return slow; } public ListNode reverse(ListNode head){ ListNode prev=null; ListNode curr=head; while(curr!=null){ ListNode next=curr.next; curr.next=prev; prev=curr; curr=next; } return prev; } }
Solution:
- Steps: 1. Find the middle element of the linked list (facilitate the inversion of the second half); 2. Reverse the second half; 3. Compare whether the first half and the second half are equal
- 1. Find the middle element of the linked list (easy to reverse in the second half): use the fast and slow pointer. The slow pointer takes one step and the fast pointer takes two steps. When the fast pointer comes to the end, the slow pointer goes to the middle position.
- 2. Reverse the second half: use a node to save the previous node, so that the current node refers to the previous node, and then move forward. The previous node is equal to the current node and the current node is equal to the next node.
- 3. Compare whether the first half and the second half are equal: compare whether the elements of the two paragraphs are equal. If there is an inequality, it is not a palindrome linked list, otherwise it is a palindrome
- N is the length of the linked list. The time complexity is O(n) and the space complexity is O(n)
2022-1-28
Sword finger Offer II 028 Flatten multilevel bidirectional linked list
Topics and examples
In the multi-level bidirectional linked list, in addition to the pointer to the next node and the previous node, it also has a sub linked list pointer, which may point to a separate bidirectional linked list. These sub lists may also have one or more of their own sub items, and so on to generate multi-level data structures, as shown in the following example.
For the head node located at the first level of the list, please flatten the list, that is, flatten such a multi-level two-way linked list into an ordinary two-way linked list, so that all nodes appear in a single-level double linked list.
Example 1:
Input: head = [1,2,3,4,5,6, null, null, 7,8,9,10, null, null, 11,12]
Output: [1,2,3,7,8,11,12,9,10,4,5,6]
Example 2:
Input: head = [1,2,null,3]
Output: [1,3,2]
Explanation:
The entered multi-level list is shown in the following figure:
1—2---NULL
|
3—NULL
Example 3:
Input: head = []
Output: []
How to represent a multi-level linked list in a test case?
Take example 1:
1—2---3—4---5—6–NULL
|
7—8---9—10–NULL
|
11–12–NULL
After serializing each of these levels:
[1,2,3,4,5,6,null]
[7,8,9,10,null]
[11,12,null]
In order to serialize each level together, we need to add a null element in each level to indicate that no node is connected to the parent node of the previous level.
[1,2,3,4,5,6,null]
[null,null,7,8,9,10,null]
[null,11,12,null]
Merge all serialization results and remove null at the end.
[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Tips:
The number of nodes shall not exceed 1000
1 <= Node.val <= 105
code:
/* // Definition for a Node. class Node { public int val; public Node prev; public Node next; public Node child; }; */ class Solution { public Node flatten(Node head) { dfs(head); return head; } public Node dfs(Node node){ Node cur=node; //Record the last node of the linked list Node last=null; while(cur!=null){ //Next indicates the next node Node next=cur.next; //If there are child nodes, process the child nodes first if(cur.child!=null){ //Child node last node Node childLast=dfs(cur.child); next=cur.next; //Connect node to child cur.next=cur.child; cur.child.prev=cur; //If next is not empty, connect last with next if(next!=null){ childLast.next=next; next.prev=childLast; } //Set child to null cur.child=null; //The last node becomes the last node of the child node last=childLast; }else{ //If there are no child nodes, the last node is the current node last=cur; } cur=next; } return last; } }
Solution:
- In depth search, if the linked list has sub linked list, the sub linked list will be added to the back of the current node and recursive in turn.
- Specifically: disconnect the node from the next node of the node, connect the node with the child, and connect the last node of the linked list with the next.
- N is the number of nodes in the linked list. The time complexity is O(n) and the space complexity is O(n).
Sword finger Offer II 030 Insert, delete, and random access are all O(1) containers
Topics and examples
Design a data structure that supports the following operations under the average time complexity O(1):
insert(val): returns true when the element val does not exist, and inserts the item into the collection; otherwise, returns false.
remove(val): returns true when the element val exists and removes the item from the collection; otherwise, returns false.
getRandom: returns an item in an existing collection at random. Each element should have the same probability of being returned.
Example:
Input: inputs = ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output: [null, true, false, true, 2, true, false, 2]
Explanation:
RandomizedSet randomSet = new RandomizedSet(); // Initialize an empty collection
randomSet.insert(1); // Inserts a 1 into the collection. Returning true indicates that the 1 was successfully inserted
randomSet.remove(2); // Returns false, indicating that 2 does not exist in the collection
randomSet.insert(2); // Inserting 2 into the collection returns true. The collection now contains [1,2]
randomSet.getRandom(); // getRandom should return 1 or 2 randomly
randomSet.remove(1); // Removing 1 from the collection returns true. The collection now contains [2]
randomSet.insert(2); // 2 is already in the collection, so false is returned
randomSet.getRandom(); // Since 2 is the only number in the collection, getRandom always returns 2
Tips:
-231 <= val <= 231 - 1
Make a maximum of 2 * 105 insert, remove and getRandom method calls
When the getRandom method is called, there is at least one element in the collection
code:
class RandomizedSet { Set<Integer> set=new HashSet<Integer>(); /** Initialize your data structure here. */ public RandomizedSet() { } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(set.add(val)){ return true; } return false; } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(set.remove(val)){ return true; } return false; } /** Get a random element from the set. */ public int getRandom() { List <Integer> list = new ArrayList<Integer>(set); int n=list.size(); return list.get(new Random().nextInt(n)); } } /** - Your RandomizedSet object will be instantiated and called as such: - RandomizedSet obj = new RandomizedSet(); - boolean param_1 = obj.insert(val); - boolean param_2 = obj.remove(val); - int param_3 = obj.getRandom(); */
Solution:
Using set array, if there are duplicate values, the addition will fail; If no value is specified, the removal fails.
- Take out the element at the specified position from set, and turn set into list. Use the get method of list
- The time complexity is O (1) and the space complexity is O(n)
3, Data structure
1. Introduction to data structure
2022-1-11
217. There are duplicate elements
Topics and examples
Given an integer array, determine whether there are duplicate elements.
If a value exists and appears in the array at least twice, the function returns true. If each element in the array is different, false is returned.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
code
class Solution { public boolean containsDuplicate(int[] nums) { boolean flag=false; Arrays.sort(nums); for(int i=0;i<nums.length-1;i++){ if(nums[i]==nums[i+1]){ flag=true; break; } } return flag; } }
Problem solution
- Double loops can be used to find duplicate elements in the array, but in this case, the time complexity is very large.
- First sort the data, then judge whether the adjacent numbers are equal, and judge whether there are duplicate elements.
- Flag is a flag to judge whether there are duplicate elements. The initial value is false. If the adjacent elements are equal, flag=true.
- The time complexity is O (n) and the space complexity is O(1).
53. Maximum subarray and
Topics and examples
Give you an integer array nums. Please find a continuous sub array with the largest sum (the sub array contains at least one element) and return its maximum sum.
A subarray is a contiguous part of an array.
Example 1:
Input: num = [- 2,1, - 3,4, - 1,2,1, - 5,4]
Output: 6
Explanation: the maximum sum of continuous subarray [4, - 1,2,1] is 6.
Example 2:
Input: num = [1]
Output: 1
Example 3:
Input: num = [5,4, - 1,7,8]
Output: 23
Tips:
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
code:
class Solution { public int maxSubArray(int[] nums) { int []a=new int[nums.length+1]; a[0]=nums[0]; for(int i=1;i<nums.length;i++){ if(a[i-1]+nums[i]>nums[i]){ a[i]=a[i-1]+nums[i]; }else{ a[i]=nums[i]; } } int max=a[0]; for(int i=1;i<nums.length;i++){ if(a[i]>max){ max=a[i]; } } return max; } }
Solution:
- Set an array a to calculate the maximum subarray sum. By comparing the sum of the previous a array value and the current num value with the previous num value, whoever is older will be assigned to the current a[i].
- a[i]=a[i-1]+nums[i]>nums[i]?a[i-1]+nums[i]:nums[i]
- Find the maximum value in array a and return.
- The time complexity is O (n), and the space complexity is O (n)
2022-1-12
1. Sum of two numbers
Topics and examples
Given an integer array nums and an integer target value target, please find the two integers with and as the target value target in the array and return their array subscripts.
You can assume that each input will correspond to only one answer. However, the same element in the array cannot appear repeatedly in the answer.
You can return answers in any order.
Example 1:
Input: num = [2,7,11,15], target = 9
Output: [0,1]
Explanation: because num [0] + num [1] = = 9, return [0, 1].
Example 2:
Input: num = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: num = [3,3], target = 6
Output: [0,1]
Tips:
2 <= nums.length <= 1^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
There will only be one valid answer
code:
class Solution { public int[] twoSum(int[] nums, int target) { int a[]=new int[2]; for(int i=0;i<nums.length-1;i++) { for(int j=i+1;j<nums.length;j++) { if(nums[i]+nums[j]==target) { a[0]=i; a[1]=j; break; } } } return a; } }
Solution:
- If the sum of two numbers is equal to the target value, the subscripts of those two numbers are stored in the array.
- The time complexity is O(n), and the space complexity is O(n)
88. Merge two ordered arrays
Topics and examples
Give you two integer arrays nums1 and nums2 in non decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Please merge nums2 into nums1 so that the merged array is also arranged in non decreasing order.
Note: finally, the merged array should not be returned by the function, but stored in the array nums1. In order to deal with this situation, the initial length of nums1 is m + n, where the first m elements represent the elements that should be merged, and the last n elements are 0, which should be ignored. The length of nums2 is n.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: it is necessary to combine [1,2,3] and [2,5,6].
The merging result is [1,2,2,3,5,6], where the elements in bold italics are the elements in nums1.
Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: need to merge [1] and [].
The combined result is [1].
Example 3:
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: the arrays to be merged are [] and [1].
The combined result is [1].
Note that there are no elements in nums1 because m = 0. The only remaining 0 in nums1 is to ensure that the merged results can be successfully stored in nums1.
code
class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { for(int i=m;i<nums1.length;i++){ nums1[i]=nums2[i-m]; } Arrays.sort(nums1); } }
Solution:
- Add the array nums2 to nums1, and then use arrays Sort() function sort
- The time complexity is O (n), and the space complexity is O(1)
2022-1-13
350. Intersection of two arrays II
Topics and examples
Here are two integer arrays nums1 and nums2. Please return the intersection of the two arrays in the form of array. The number of occurrences of each element in the returned result should be consistent with the number of occurrences of elements in both arrays (if the number of occurrences is inconsistent, consider taking the smaller value). The order of output results can be ignored.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Tips:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
code:
class Solution { public int[] intersect(int[] nums1, int[] nums2) { Arrays.sort(nums1); Arrays.sort(nums2); int index1=0,index2=0; ArrayList<Integer> list = new ArrayList<Integer>(); while(index1!=nums1.length&&index2!=nums2.length){ if(nums1[index1]==nums2[index2]){ list.add(nums1[index1]); index1++; index2++; }else if(nums1[index1]>nums2[index2]){ index2++; }else if(nums1[index1]<nums2[index2]){ index1++; } } int[] a = new int[list.size()]; for(int i = 0;i<list.size();i++){ a[i] = list.get(i); } return a; } }
Solution:
- Double pointers, starting with the subscript 0. For comparison, if the value of array 1 is greater than array 2, index2 + +; If the value of array 1 is less than array 2, index1 + +;
- Because the number of overlapping arrays is unknown and cannot be defined as an array of fixed length, the variable array ArrayList is defined and then converted back to the int array with a for loop.
- The time complexity is O(n), and the space complexity is O(n)
121. The best time to buy and sell stocks
Topics and examples
Given an array of prices, its ith element price [i] represents the price of a given stock on day I.
You can only choose to buy this stock one day and sell it on a different day in the future. Design an algorithm to calculate the maximum profit you can make.
Return the maximum profit you can make from this transaction. If you can't make any profit, return 0.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: buy on day 2 (stock price = 1) and sell on day 5 (stock price = 6). Maximum profit = 6-1 = 5.
Note that the profit cannot be 7-1 = 6, because the selling price needs to be greater than the buying price; At the same time, you can't sell stocks before buying.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: in this case, no transaction is completed, so the maximum profit is 0.
Tips:
1 <= prices.length <= 105
0 <= prices[i] <= 104
code:
class Solution { public int maxProfit(int[] prices) { int []dp=new int[prices.length]; dp[0]=prices[0]; int max=0; for(int i=1;i<prices.length;i++){ dp[i]=(dp[i-1]<prices[i])? dp[i-1]:prices[i]; max=(prices[i]-dp[i])>max? prices[i]-dp[i]:max; } return max; } }
Solution:
- In dynamic programming, dp array is the lowest value recorded before point I, dp[i]=min(dp[i-1],prices[i]). The minimum value before point I is the minimum value between the minimum value before point i-1 and the current stock value.
- The maximum profit is the minimum value before the current price minus the current price. If this time is greater than the previous maximum, the previous maximum is replaced.
- The time complexity is O(n), traversing the array;
- The space complexity is O (n), and the auxiliary array dp.
2022-1-14
118. Yanghui triangle
Topics and examples
Given a nonnegative integer numRows, the first numRows of the Yang Hui triangle are generated.
In the Yang Hui triangle, each number is the sum of its upper left and upper right numbers.
Example 1:
Input: numRows = 5
Output: [[1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
Tip: 1 < = NumRows < = 30
code:
class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> list=new ArrayList<List<Integer>>(); for(int i=0;i<numRows;i++){ List<Integer> li=new ArrayList<Integer>(); for(int j=0;j<i+1;j++){ if(j==0||j==i){ li.add(1); }else{ li.add(list.get(i-1).get(j-1)+list.get(i-1).get(j)); } } list.add(li); } return list; } }
Solution:
- List < list < integer > > is used to store two-dimensional variable arrays. List < integer > is a one-dimensional array of each row.
- The first and last numbers of each row are 1. The number in row i and column j is equal to the sum of the number in row i-1 and column j-1 and the number in row i-1 and column j.
- There are two implementation classes of list, one is ArrayList and the other is LinkedList. Here we use the array – ArrayList,add() to add the value, and get () to get the value of a certain location.
566. Reshaping the matrix
Topics and examples
In MATLAB, there is a very useful function reshape, which can reshape an m x n matrix into another new matrix with different size (r x c), but retain its original data.
Give you an m x n matrix represented by a two-dimensional array mat, and two positive integers r and c, which respectively represent the number of rows and columns of the matrix you want to reconstruct.
The reconstructed matrix needs to fill all elements of the original matrix in the same row traversal order.
If the reshape operation with given parameters is feasible and reasonable, a new reshape matrix is output; Otherwise, the original matrix is output.
Example 1:
Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]
Example 2:
Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2], [3,4]]
Tips:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300
code:
class Solution { public int[][] matrixReshape(int[][] mat, int r, int c) { int m=mat.length; int n=mat[0].length; int []a=new int[(m*n)]; int [][]b=new int[r][c]; if(r*c!=m*n){ return mat; } int ans=0; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ a[ans]=mat[i][j]; ans++; } } int k=0; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ b[i][j]=a[k]; k++; } } return b; } }
Solution:
- First, find out whether it can be reshaped. The condition is to see whether the number of numbers of the original matrix is equal to that of the transformation matrix, that is, whether the number of rows of the original matrix multiplied by the number of columns is equal to that of the transformation matrix multiplied by the number of columns. If not, return to the original matrix. If equal, perform the following operations.
- The original two-dimensional matrix is transformed into one-dimensional matrix, which is convenient for changing the value of the matrix later.
- Reshape with a for loop.
- The time complexity is O(n^2) and the space complexity is O(n^2)
2022-1-17
73. Matrix zeroing
Topics and examples
Given a matrix of m x n, if an element is 0, all elements in its row and column are set to 0. Please use the in place algorithm.
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1], [0,0,0], [1,0,1]]
Example 2:
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0], [0,4,5,0], [0,3,1,0]]
Tips:
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-231 <= matrix[i][j] <= 231 - 1
code:
class Solution { public void setZeroes(int[][] matrix) { int n=matrix.length; int m=matrix[0].length; boolean []row=new boolean[n]; boolean []col=new boolean[m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(matrix[i][j]==0){ row[i]=col[j]=true; } } } for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(row[i]||col[j]){ matrix[i][j]=0; } } } } }
Solution:
- Set two flag arrays to flag whether a row or column has zero, and set it to true if any.
- Traverse again. When the flag array is true, set the number in the matrix array to zero.
- The time complexity is O (nm), and the space complexity is O (m+n)
36. Effective Sudoku
Topics and examples
Please judge whether a 9 x 9 Sudoku is effective. You only need to verify whether the following numbers have been filled in according to the rules.
The numbers 1-9 can only appear once in each line.
The numbers 1-9 can only appear once in each column.
The numbers 1-9 can only appear once in each 3x3 uterus separated by a thick solid line. (please refer to the example diagram)
be careful:
An effective Sudoku (partially filled) is not necessarily solvable.
You only need to verify whether the filled numbers are valid according to the above rules.
Use '.' for blank space express.
Example 1:
Input: board=
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true
Example 2:
Input: board=
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false
Explanation: except that the first number in the first line is changed from 5 to 8, other numbers in the space are the same as example 1. However, due to the existence of two 8's in the 3x3 uterus in the upper left corner, this Sudoku is invalid.
Tips:
board.length == 9
board[i].length == 9
board[i][j] is a digit (1-9) or '.'
code:
class Solution { public boolean isValidSudoku(char[][] board) { int [][]rows=new int[9][9]; int [][]cols=new int[9][9]; int [][][]sub=new int[3][3][9]; for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ char tmp=board[i][j]; if(tmp!='.'){ int index=tmp-'0'-1; rows[i][index]++; cols[j][index]++; sub[i/3][j/3][index]++; if(rows[i][index]>1|| cols[j][index]>1|| sub[i/3][j/3][index]>1){ return false; } } } } return true; } }
Solution:
- rows,cols and sub arrays are used to count the number of occurrences of 1-9 in rows, columns and nine cells.
- If the number of occurrences is greater than 1, there are duplicate numbers.
- Because the number of numbers in the matrix is fixed, the time complexity is O(1) and the space complexity is O(1)
2022-1-18
387. The first unique character in a string
Topics and examples
Given a string, find its first non repeating character and return its index. If it does not exist, - 1 is returned.
Example:
s = "leetcode"
Return 0
s = "loveleetcode"
Return 2
code:
class Solution { public int firstUniqChar(String s) { Map<Character,Integer> map=new LinkedHashMap<>(); for(int i=0;i<s.length();i++){ map.put(s.charAt(i) ,map.getOrDefault(s.charAt(i),0)+1); } char ans='0'; //Traverse the map and find the key value through the value equal to 1 for(Map.Entry<Character,Integer> entry:map.entrySet()){ char ch=entry.getKey(); int num=entry.getValue(); if(num==1){ ans=ch; break; } } for(int i=0;i<s.length();i++){ if(ans==s.charAt(i)){ return i; } } return -1; } }
Solution:
- map records characters and the number of times characters appear. LinkedHashMap can be output in the order of input. HashMap is out of order.
- Find the first character with 1 occurrences, that is, traverse the map to obtain the key and value values, and the key value corresponding to value=1
- Then traverse the string to find the subscript of this character.
- One of the ways to traverse a map: map Entry<Character,Integer> entry:map. entrySet()
- N represents the number of characters of string s, with time complexity of O(n) and space complexity of O(n)
383. Ransom letter
Topics and examples
Give you two strings: ransomNote and magazine. Judge whether ransomNote can be composed of characters in magazine.
If yes, return true; Otherwise, false is returned.
Each character in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Tips:
1 <= ransomNote.length, magazine.length <= 105
ransomNote and magazine are composed of lowercase English letters
code:
class Solution { public boolean canConstruct(String ransomNote, String magazine) { int n=ransomNote.length(); int m=magazine.length(); int []a=new int[26]; if(n>m){ return false; } for(int i=0;i<m;i++){ a[magazine.charAt(i)-'a']++; } for(int i=0;i<n;i++){ a[ransomNote.charAt(i)-'a']--; } for(int i = 0; i < 26; i++) { if(a[i]<0){ return false; } } return true; } }
Solution:
- If the length of ransomNote is greater than that of magazine, it must not meet the conditions
- The int array is used to count the number of characters appearing. The characters appearing in magazine are plus one, while the characters appearing in ransomNote are minus one. If the number of characters appearing in int array is less than 0, it means that the number of characters appearing in ransomNote is greater than the number of characters appearing in magazine, which does not meet the conditions
- The time complexity is O(m+n), where m is the length of the string ransomNote and N is the length of the string magazine
- Spatial complexity: O(∣ S ∣), S is the character set. In this question, S is all lowercase English letters, so ∣ S ∣ = 26.
242. Valid acronyms
and 383. Ransom letter similar
Given two strings s and t, write a function to judge whether t is an alphabetic ectopic word of s.
Note: if each character in S and t appears the same number of times, s and T are called alphabetic words.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Tips:
1 <= s.length, t.length <= 5 * 104
s and t contain only lowercase letters
code:
class Solution { public boolean isAnagram(String s, String t) { int n=s.length(); int m=t.length(); int []a=new int[26]; if(n!=m){ return false; } for(int i=0;i<n;i++){ a[s.charAt(i)-'a']++; } for(int i=0;i<m;i++){ a[t.charAt(i)-'a']--; } for(int i = 0; i < 26; i++) { if(a[i]!=0){ return false; } } return true; } }
2022-1-19
141. Circular linked list
Topics and examples
Give you a head node of the linked list to judge whether there are links in the linked list.
If there is a node in the linked list that can be reached again by continuously tracking the next pointer, there is a ring in the linked list. In order to represent the links in a given linked list, the evaluation system uses the integer pos to represent the position where the tail of the linked list is connected to the linked list (the index starts from 0). If pos is - 1, there is no ring in the linked list. Note: pos is not passed as a parameter, but only to identify the actual situation of the linked list.
Returns true if there are links in the linked list. Otherwise, false is returned.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: there is a ring in the linked list, and its tail is connected to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: there is a ring in the linked list, and its tail is connected to the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: there are no links in the linked list.
Tips:
The number range of nodes in the linked list is [0, 104]
-105 <= Node.val <= 105
pos is - 1 or a valid index in the linked list.
code:
/** - Definition for singly-linked list. - class ListNode { - int val; - ListNode next; - ListNode(int x) { - val = x; - next = null; - } - } */ public class Solution { public boolean hasCycle(ListNode head) { Set<ListNode> set=new HashSet<>(); while(head!=null){ if(!set.add(head)){ return true; } head=head.next; } return false; } }
Solution:
- Use the hash table to store the linked list node. If you traverse to a node and it already exists in the hash table, it means that the linked list is a ring linked list. Otherwise, add the node to the hash table. If it already exists in the hash table, set Add (head) fails to join and returns false. If it does not exist in the hash table, it returns true and joins successfully.
- N is the number of nodes, the time complexity is O(n), and the space complexity is O(n)
21. Merge two ordered linked lists
Topics and examples
Merge the two ascending linked lists into a new ascending linked list and return. The new linked list is composed of all nodes of a given two linked lists.
Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: l1 = [], l2 = []
Output: []
Example 3:
Input: l1 = [], l2 = [0]
Output: [0]
Tips:
The number of nodes in the two linked lists ranges from [0, 50]
-100 <= Node.val <= 100
l1 and l2 are arranged in non decreasing order
code:
/** - Definition for singly-linked list. - public class ListNode { - int val; - ListNode next; - ListNode() {} - ListNode(int val) { this.val = val; } - ListNode(int val, ListNode next) { this.val = val; this.next = next; } - } */ class Solution { public ListNode mergeTwoLists(ListNode list1, ListNode list2) { if(list1==null){ return list2; }else if(list2==null){ return list1; }else if(list1.val<list2.val){ list1.next=mergeTwoLists(list1.next,list2); return list1; }else{ list2.next=mergeTwoLists(list1,list2.next); return list2; } } }
Solution:
- Recursion. If one of the linked lists is empty, another linked list will be returned. First, compare the size of the first node of the two linked lists. Who is smaller is the first node of the new linked list.
- In turn, the next node is compared with the node of another linked list.
- Time complexity: O(n+m), where N and m are the lengths of the two linked lists respectively
- Spatial complexity: O(n+m), where N and m are the lengths of the two linked lists respectively
203. Remove linked list elements
Topics and examples
Give you a head node of the linked list and an integer val. please delete all nodes in the linked list that meet the requirements Val = = Val node and returns a new header node.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = [7,7,7,7], val = 7
Output: []
Tips:
The number of nodes in the list is in the range [0, 104]
1 <= Node.val <= 50
0 <= val <= 50
code:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeElements(ListNode head, int val) { if(head==null){ return head; } head.next=removeElements(head.next, val); return head.val==val?head.next:head; } }
Solution:
- Recursion: end condition of recursion and recursive loop body.
- When the node points to null, the loop ends, and the next node of the node is the loop body. If the first node is that value, the first node is head Next, if not, the first node head
- Time complexity: O(n), where n is the length of the linked list. The recursive process needs to traverse the linked list once.
- Spatial complexity: O(n), where n is the length of the linked list. The space complexity mainly depends on the recursive call stack, which will not exceed n layers at most.
2022-1-20
206. Reverse linked list
Topics and examples
Give you the head node of the single linked list. Please reverse the linked list and return the reversed linked list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Tips:
The number range of nodes in the linked list is [0, 5000]
-5000 <= Node.val <= 5000
code:
/** - Definition for singly-linked list. - public class ListNode { - int val; - ListNode next; - ListNode() {} - ListNode(int val) { this.val = val; } - ListNode(int val, ListNode next) { this.val = val; this.next = next; } - } */ class Solution { public ListNode reverseList(ListNode head) { ListNode prev=null; ListNode curr=head; while(curr!=null){ ListNode next=curr.next; curr.next=prev; prev=curr; curr=next; } return prev; } }
Solution:
- Iterative method, reverse the linked list, so that the latter node refers to the previous node. You need to save the previous node and the current node, and then point to the previous node. In the future, the previous node becomes the current node, and the current node waits for the next node until the current node is null.
- N is the length of the linked list. The time complexity is O(n) and the space complexity is O(1)
83. Delete duplicate elements in the sorting linked list
Topics and examples
There is a linked list arranged in ascending order. Give you the head node of the linked list. Please delete all duplicate elements so that each element appears only once.
Returns a linked list of results in the same ascending order.
Example 1:
Input: head = [1,1,2]
Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3]
Output: [1,2,3]
Tips:
The number of nodes in the linked list is within the range [0, 300]
-100 <= Node.val <= 100
The title data ensures that the linked list has been arranged in ascending order
code:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { if(head==null){ return head; } ListNode cur=head; //cur.next==null indicates that it is the last element of the linked list while(cur.next!=null){ if(cur.val==cur.next.val){ cur.next=cur.next.next; }else{ cur=cur.next; } } return head; } }
Solution:
- If the current element and the latter element are equal, the current element points to the latter element of the latter element, which is curr next=curr. next. next. If not, traverse backward.
- Note that the loop condition is that the current element point is not null, that is, it is not the last element in the linked list. The loop ends when the last element is traversed.
- The length of the linked list is n, the time complexity is O (n), and the space complexity is O(1)
2022-1-21
20. Valid brackets
Topics and examples
Given a string s that only includes' (',') ',' {','} ',' [','] ', judge whether the string is valid.
Valid strings must meet:
The left parenthesis must be closed with the same type of right parenthesis.
The left parentheses must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "() [] {}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Tips:
1 <= s.length <= 104
s consists only of parentheses' () [] {} '
code:
class Solution { public boolean isValid(String s) { if(s.isEmpty()){ return true; } Stack<Character> stack=new Stack<Character>(); for(char c:s.toCharArray()){ if(c=='('){ stack.push(')'); }else if(c=='['){ stack.push(']'); }else if(c=='{'){ stack.push('}'); }else if(stack.empty()||c!=stack.pop()){ return false; } } if(stack.empty()){ return true; } return false; } }
Solution:
- Stack: when encountering the left bracket, put the corresponding right bracket into the stack. When encountering the right bracket, take the element at the top of the stack out of the stack for matching. If it is equal, continue. If it is not equal, it indicates that the bracket does not match. When the last element stack is empty, the following bracket cannot match, indicating that the bracket does not match.
- If the last match is made, the stack will be empty, indicating that the brackets match. If the string is empty, it must match.
- N is the length of the string, the time complexity is O(n), and the space complexity is O(n)
232. Implement queue with stack
Topics and examples
Please use only two stacks to implement the first in first out queue. The queue should support all operations supported by the general queue (push, pop, peek, empty):
Implement MyQueue class:
void push(int x) pushes element X to the end of the queue
int pop() removes the element from the beginning of the queue and returns it
int peek() returns the element at the beginning of the queue
boolean empty() returns true if the queue is empty; Otherwise, false is returned
explain:
You can only use standard stack operations -- that is, only push to top, peek/pop from top, size, and is empty operations are legal.
Your language may not support stacks. You can use list or deque (double ended queue) to simulate a stack, as long as it is a standard stack operation.
Advanced:
Can you implement a queue with a time complexity of O(1) for each operation? In other words, the total time complexity of performing n operations is O(n), even if one of them may take a long time.
Example:
Input:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output:
[null, null, null, 1, 1, false]
Explanation:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
Tips:
1 <= x <= 9
Call push, pop, peek and empty up to 100 times
It is assumed that all operations are valid (for example, an empty queue will not call pop or peek operations)
code:
class MyQueue { private int front; private Stack<Integer> s1 = new Stack<>(); private Stack<Integer> s2 = new Stack<>(); public MyQueue() { } public void push(int x) { if(s1.empty()){ front=x; } while(!s1.isEmpty()){ s2.push(s1.pop()); } s2.push(x); while(!s2.isEmpty()){ s1.push(s2.pop()); } } public int pop() { int p=s1.peek(); s1.pop(); if(!s1.empty()){ front=s1.peek(); } return p; } public int peek() { return front; } public boolean empty() { return s1.isEmpty(); } } /** - Your MyQueue object will be instantiated and called as such: - MyQueue obj = new MyQueue(); - obj.push(x); - int param_2 = obj.pop(); - int param_3 = obj.peek(); - boolean param_4 = obj.empty(); */
Solution:
- Two stacks are used to realize the queue. The stack is "first in first out" and the queue is "first in first out". melt
- push into stack: first put the elements in stack 1 out of the stack into stack 2, then put the elements in stack 2, and then put the elements in stack 2 into stack 1, so that the later put elements can be ranked behind to realize FIFO.
- Out of stack pop: first obtain the top element of the stack to facilitate return. Then stack 1 goes out of the stack and the first element is removed. Then the first element becomes the current top element of the stack.
- Stack top element peek: define the global variable front outside the function, and front points to the stack top.
- empty: use the original method of stack - isEmpty()
- The number of elements in the stack is n, the for loop, and the time complexity is O(n)
- Two stacks are used, and the space complexity is O(2n)=O(n)
2022-1-22
144. Preorder traversal of binary tree
Topics and examples
Give you the root node of the binary tree, root, and return the preorder traversal of its node value.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [1,2]
Example 5:
Input: root = [1,null,2]
Output: [1,2]
Tips:
The number of nodes in the tree is in the range [0, 100]
-100 <= Node.val <= 100
code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { //Preorder traversal is root node - > left node - > right node public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list=new ArrayList<Integer>(); preorder(root,list); return list; } public void preorder(TreeNode root,List<Integer> list){ if(root==null){ return; } list.add(root.val); preorder(root.left,list); preorder(root.right,list); } }
94. Middle order traversal of binary tree
Topics and examples
Given the root node of a binary tree, root, returns its middle order traversal.
Example 1:
Input: root = [1,null,2,3]
Output: [1,3,2]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [2,1]
Example 5:
Input: root = [1,null,2]
Output: [1,2]
Tips:
The number of nodes in the tree is in the range [0, 100]
-100 <= Node.val <= 100
code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { //Middle order traversal is left node - > root node - > right node public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list=new ArrayList<Integer>(); inorder(root,list); return list; } public void inorder(TreeNode root,List<Integer> list){ if(root==null){ return; } inorder(root.left,list); list.add(root.val); inorder(root.right,list); } }
145. Post order traversal of binary tree
Topics and examples
Give you the root node of a binary tree, root, and return the subsequent traversal of its node value.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Tips:
The number of nodes in the tree is in the range [0, 100]
-100 <= Node.val <= 100
code:
/** - Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode() {} - TreeNode(int val) { this.val = val; } - TreeNode(int val, TreeNode left, TreeNode right) { - this.val = val; - this.left = left; - this.right = right; - } - } */ class Solution { //Post order traversal is the left node -- > right node -- > root node public List<Integer> postorderTraversal(TreeNode root) { List<Integer> list=new ArrayList<Integer>(); postorder(root,list); return list; } public void postorder(TreeNode root,List<Integer> list){ if(root==null){ return; } postorder(root.left,list); postorder(root.right,list); list.add(root.val); } }
Three in one problem solving
- Preorder traversal is root node - > left node - > right node; Middle order traversal is left node - > root node - > right node; Post order traversal is left node – > right node – > root node (memory method: what order traversal is it, root j point)
2022-1-24
102. Sequence traversal of binary tree*
Topics and examples
Give you the root node of the binary tree, root, and return the sequence traversal of its node value. (that is, access all nodes from left to right layer by layer).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3], [9,20], [15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Tips:
The number of nodes in the tree is in the range [0, 2000]
-1000 <= Node.val <= 1000
code:
/** - Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode() {} - TreeNode(int val) { this.val = val; } - TreeNode(int val, TreeNode left, TreeNode right) { - this.val = val; - this.left = left; - this.right = right; - } - } */ class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> list=new ArrayList<List<Integer>>(); if(root==null){ return list; } Queue<TreeNode> q=new LinkedList<TreeNode>(); q.offer(root);//Enter the queue while(!q.isEmpty()){ List<Integer> li=new ArrayList<Integer>(); int n=q.size();//Get queue length for(int i=0;i<n;i++){ TreeNode node=q.poll();//Out of queue li.add(node.val); if(node.left!=null){ q.offer(node.left);//Enter the queue } if(node.right!=null){ q.offer(node.right);//Enter the queue } } list.add(li); } return list; } }
Solution:
- Breadth first search (queue)
- The root node enters the queue, then traverses the queue, lists the queue, and prints the node value. Add the left and right nodes of the node into the queue and continue with the above steps.
- Each point enters and exits the team once, and the time complexity is O (n)
- The number of elements in the queue does not exceed n, and the space complexity is O(n)
104. Maximum depth of binary tree
Topics and examples
Given a binary tree, find its maximum depth.
The depth of the binary tree is the number of nodes on the longest path from the root node to the farthest leaf node.
Note: leaf nodes refer to nodes without child nodes.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
Returns its maximum depth 3.
code:
class Solution { public int maxDepth(TreeNode root) { if(root==null){ return 0; }else{ int l=maxDepth(root.left); int r=maxDepth(root.right); return Math.max(l,r)+1; } } }
Solution:
- Depth first search (recursion). The height of binary tree is equal to the maximum of the height of left subtree and right subtree plus one.
- Time complexity: O(n), where n is the number of binary tree nodes. Each node is traversed only once in recursion.
- Spatial complexity: O(height), where height represents the height of the binary tree. Recursive functions need stack space, which depends on the depth of recursion, so the space complexity is equivalent to the height of binary tree.
101. Symmetric binary tree
Topics and examples
Give you the root node of a binary tree, root, and check whether it is axisymmetric.
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
Tips:
The number of nodes in the tree is in the range [1, 1000]
-100 <= Node.val <= 100
code:
/** - Definition for a binary tree node. - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode() {} - TreeNode(int val) { this.val = val; } - TreeNode(int val, TreeNode left, TreeNode right) { - this.val = val; - this.left = left; - this.right = right; - } - } */ class Solution { public boolean isSymmetric(TreeNode root) { return check(root,root); } public boolean check(TreeNode p,TreeNode q){ //If only root is empty, it must be symmetric if(p==null&&q==null){ return true; } //If one side is null and the other side has a value, it must be asymmetric if(p==null||q==null){ return false; } return p.val==q.val&&check(p.right,q.left)&&check(p.left,q.right); } }
Solution:
- Compare the mirrors of the left subtree and the right subtree. If they are the same, they are symmetrical, otherwise they are asymmetric. Implementation method: set two pointers. When one pointer points to the left and the other pointer points to the right, compare whether the values are equal, and traverse the depth first
- The node number of binary tree is n, the time complexity is O(n), and the space complexity is O(n)
2. Data structure foundation
2022-1-25
136. Figures that appear only once
Given a non empty array of integers, each element appears twice except that one element appears only once. Find the element that appears only once.
Note: your algorithm should have linear time complexity. Can you do it without using extra space?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
code:
class Solution { public int singleNumber(int[] nums) { int ans=0; for(int i=0;i<nums.length;i++){ ans^=nums[i]; } return ans; } }
Solution:
- XOR can change the repeated number into 0, and the one that appears only once is 1
- The time complexity is O (n), and the space complexity is O (1)
169. Most elements
Topics and examples
Given an array of size n, find most of its elements. Most elements refer to elements that appear more than ⌊ n/2 ⌋ in the array.
You can assume that the array is non empty and that there are always many elements in a given array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
Advanced: try to design an algorithm with time complexity O(n) and space complexity O(1) to solve this problem.
code:
class Solution { public int majorityElement(int[] nums) { int n=nums.length; int num=0; Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++){ map.put(nums[i],map.getOrDefault(nums[i],0)+1); } for(Map.Entry<Integer,Integer> entry:map.entrySet()){ int key=entry.getKey(); int value=entry.getValue(); if(value>n/2){ num=key; break; } } return num; } }
Solution:
- Use map to record numbers and the number of times numbers appear
- The time complexity is O (n), and the space complexity is O (n)
2022-1-26
75. Color classification
Topics and examples
Given an array num of n elements including red, white and blue, they are sorted in place so that the elements of the same color are adjacent and arranged in the order of red, white and blue.
We use integers 0, 1, and 2 to represent red, white, and blue, respectively.
You must solve this problem without using the sort function of the library.
Example 1:
Input: num = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:
Input: num = [2,0,1]
Output: [0,1,2]
Tips:
n == nums.length
1 <= n <= 300
Num [i] is 0, 1, or 2
Advanced:
Can you solve this problem without using the sorting function in the code base?
Can you think of a one pass scan algorithm that uses only constant space?
code:
class Solution { public void sortColors(int[] nums) { int n=nums.length; //Bubble sorting for(int i=0;i<n-1;i++){ for(int j=i+1;j<n;j++){ if(nums[j]<nums[i]){ int t=nums[j]; nums[j]=nums[i]; nums[i]=t; } } } } }
Solution:
- The essence of this problem is sorting. There are many kinds of sorting, counterfeiting, fast sorting and so on
- The time complexity is O (n2) and the space complexity is O(1)
706. Design hash mapping
Topics and examples
Design a hash map without using any built-in hash table library.
Implement MyHashMap class:
MyHashMap() initializes the object with an empty map
void put(int key, int value) inserts a key value pair (key, value) into HashMap. If the key already exists in the map, update its corresponding value.
int get(int key) returns the value mapped by a specific key; If the mapping does not contain the mapping of key, return - 1.
void remove(key) if there is a key mapping in the mapping, remove the key and its corresponding value.
Example:
Input:
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
Output:
[null, null, null, 1, -1, null, 1, null, -1]
Explanation:
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // myHashMap is now [[1,1]]
myHashMap.put(2, 2); // myHashMap is now [[1,1], [2,2]]
myHashMap.get(1); // Return 1. Myhashmap is now [[1,1], [2,2]]
myHashMap.get(3); // Return - 1 (not found). Myhashmap is now [[1,1], [2,2]]
myHashMap.put(2, 1); // myHashMap is now [[1,1], [2,1]] (update the existing value)
myHashMap.get(2); // Return 1. Myhashmap is now [[1,1], [2,1]]
myHashMap.remove(2); // Delete the data with key 2. Myhashmap is now [[1,1]]
myHashMap.get(2); // Return - 1 (not found), myhashmap is now [[1,1]]
Tips:
0 <= key, value <= 106
The put, get, and remove methods can be called up to 104 times
code:
class MyHashMap { private class Pair{ private int key; private int value; public Pair(int key,int value){ this.key=key; this.value=value; } public int getKey(){ return key; } public void setKey(int key){ this.key=key; } public int getValue(){ return value; } public void setValue(int value){ this.value=value; } } private static final int BASE=769; private LinkedList []data; public MyHashMap() { data=new LinkedList[BASE]; for(int i=0;i<BASE;i++){ data[i]=new LinkedList<>(); } } public void put(int key, int value) { int h=hash(key); Iterator<Pair> iterator =data[h].iterator(); while(iterator.hasNext()){ Pair pair =iterator.next(); if(pair.getKey()==key){ pair.setValue(value); return; } } data[h].offerLast(new Pair(key,value)); } public int get(int key) { int h=hash(key); Iterator<Pair> iterator =data[h].iterator(); while(iterator.hasNext()){ Pair pair =iterator.next(); if(pair.getKey()==key){ return pair.value; } } return -1; } public void remove(int key) { int h=hash(key); Iterator<Pair> iterator =data[h].iterator(); while(iterator.hasNext()){ Pair pair =iterator.next(); if(pair.getKey()==key){ data[h].remove(pair); return; } } } private static int hash(int key){ return key%BASE; } } /** - Your MyHashMap object will be instantiated and called as such: - MyHashMap obj = new MyHashMap(); - obj.put(key,value); - int param_2 = obj.get(key); - obj.remove(key); */
Solution:
- First, define a class, which initializes the get and set methods, and LinkedList stores the key\value array
- put method: iterator traverses. If it is equal to the existing key, set the value to valuemr. If not, add the new key and value to the LinkedList array
- get method: iterator traverses. If it is equal to the existing key, it returns the corresponding value
- Remove method: iterator traverses. If it is equal to the existing key, remove the corresponding key and value
- Iterator: iterator < pair > iterator = data [H] iterator(); Hasnext() determines whether there is a next number; iterator .next () is the next value specified
- Time complexity: O (b/n). Where n is the number of elements in the hash table and b is the number of linked lists. Assuming that the hash values are evenly distributed, the approximate length of each linked list is b/n
- Spatial complexity: O(n+b).
2022-1-27
119. Yanghui triangle II
Given a nonnegative index rowIndex, return the rowIndex row of "Yang Hui triangle".
In the Yang Hui triangle, each number is the sum of its upper left and upper right numbers.
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0
Output: [1]
Example 3:
Input: rowIndex = 1
Output: [1,1]
Tips:
0 <= rowIndex <= 33
code:
class Solution { public List<Integer> getRow(int rowIndex) { List<List<Integer>> list=new ArrayList<List<Integer>>(); for(int i=0;i<=rowIndex;i++){ List<Integer> li=new ArrayList<>(); for(int j=0;j<i+1;j++){ if(j==0||j==i){ li.add(1); }else{ li.add(list.get(i-1).get(j-1)+list.get(i-1).get(j)); } } list.add(li); } return list.get(rowIndex); } }
Solution:
- Yang Hui triangle, the first element of each row and the latter element are 1. An element is equal to the element of the corresponding column of the previous row plus the element of the previous column of the previous row.
- The time complexity is O(rowIndex2) and the space complexity is O(n)
48. Rotate image
Given an n × The two-dimensional matrix of N represents an image. Please rotate the image 90 degrees clockwise.
You have to rotate the image in place, which means you need to modify the input two-dimensional matrix directly. Do not use another matrix to rotate the image.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,9,7], [3,6]
Example 2:
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5], [14,3,4,1], [12,6,8,9], [16,7,10,11]]
Tips:
n == matrix.length == matrix[i].length
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
code:
class Solution { public void rotate(int[][] matrix) { int n=matrix.length; int [][] ans=new int [n][n]; //Row I, column j -- > the penultimate I (n-1-i) column, row j for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ ans[j][n-1-i]=matrix[i][j]; } } //Re assign to the original array for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ matrix[i][j]=ans[i][j]; } } } }
Solution:
- Use the auxiliary array, row I, column j – > the penultimate I (n-1-i) column, row j. Then assign the auxiliary array to the original array.
- The time complexity is O (n2), and the space complexity is O (n2)
2022-2-7
240. Search two-dimensional matrix II
Write an efficient algorithm to search a target value target in m x n matrix. The matrix has the following characteristics:
The elements of each row are arranged in ascending order from left to right.
The elements of each column are arranged in ascending order from top to bottom.
Example 1:
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
Output: true
Example 2:
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
Output: false
Tips:
m == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-109 <= matrix[i][j] <= 109
All elements of each row are arranged in ascending order from left to right
All elements of each column are arranged in ascending order from top to bottom
-109 <= target <= 109
code:
class Solution { public boolean searchMatrix(int[][] matrix, int target) { for(int i=0;i<matrix.length;i++){ int left=0; int right=matrix[i].length-1; while(left<=right){ int mid=(left+right)/2; if(matrix[i][mid]==target){ return true; }else if(matrix[i][mid]<target){ left=mid+1; }else{ right=mid-1; } } } return false; } }
Problem solving;
- Binary search, because it is arranged in ascending order from left to right
- The time complexity is O (nlogn) and the space complexity is O(1)
435. Non overlapping interval
Topics and examples
Given a set of intervals, find the minimum number of intervals to be removed so that the remaining intervals do not overlap each other.
be careful:
It can be considered that the end of an interval is always greater than its starting point.
The boundaries of intervals [1,2] and [2,3] are "in contact" with each other, but do not overlap each other.
Example 1:
Input: [1,2], [2,3], [3,4], [1,3]]
Output: 1
Explanation: after removing [1,3], the remaining intervals do not overlap.
Example 2:
Input: [[1,2], [1,2], [1,2]]
Output: 2
Explanation: you need to remove two [1,2] so that the remaining intervals do not overlap.
Example 3:
Input: [[1,2], [2,3]]
Output: 0
Explanation: you don't need to remove any intervals because they are already non overlapping.
code:
class Solution { public int eraseOverlapIntervals(int[][] intervals) { if(intervals.length==0){ return 0; } Arrays.sort(intervals,new Comparator<int[]>(){ public int compare(int [] interval1,int []interval2){ //If the return value is > 0, that is, the preceding number is greater than the following number, it will be exchanged and arranged in ascending order return interval1[1]-interval2[1]; } }); int n=intervals.length; int right=intervals[0][1]; int ans=1; for(int i=0;i<n;i++){ //If the left end point of this interval does not coincide with the right end point of the previous interval, one more point will not be moved out of the interval, and the right end point will become the right end point of this interval if(intervals[i][0]>=right){ ans++; right=intervals[i][1]; } } return n-ans; } }
Solution:
- Greedy method, arrays New comparator < int [] > in sort (intervals, new comparator < int [] > () {}) can customize sorting. If the return value is > 0, that is, if the previous number is greater than the following number, it will be exchanged and arranged in ascending order
- Then make greedy selection. If the left end point of this interval does not coincide with the right end point of the previous interval, do not move out of the interval, and the right end point becomes the right end point of this interval.
- The time complexity is O(nlogn), and the ascending order requires nlogn time
- The space complexity is O(logn), and the stack space to be used for sorting
4, Dynamic programming
2022-1-11
509. Fibonacci number
Topics and examples
Fibonacci numbers are usually represented by F(n), and the sequence formed is called Fibonacci sequence. The sequence starts with 0 and 1, and each subsequent number is the sum of the first two numbers. That is:
F(0) = 0,F(1) = 1
F(n) = F(n - 1) + F(n - 2), where n > 1
Here you are n, please calculate F(n).
Example 1:
Input: 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1
Example 2:
Input: 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2
code:
class Solution { public int fib(int n) { if(n==0){ return 0; } if(n==1){ return 1; } return fib(n-1)+fib(n-2); } }
Solution:
- According to the recursive method, F(0) = 0, f (1) = 1, f (n) = f (n - 1) + F (n - 2), where n > 1
- The time complexity is O(2^n), and the space complexity is O(1)
1137. N th teponacci number
Topics and examples
The teponacci sequence Tn is defined as follows:
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 when n > = 0
Here is the integer n. please return the value of the nth teponacci number Tn.
Example 1:
Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
Example 2:
Input: n = 25
Output: 1389537
Error code (timeout)
class Solution { public int tribonacci(int n) { if(n==0){ return 0; } if(n==1||n==2){ return 1; } return tribonacci(n-1)+tribonacci(n-2)+tribonacci(n-3); } }
code:
class Solution { public int tribonacci(int n) { if(n==0){ return 0; } if(n==1||n==2){ return 1; } int p=0,q=0,r=1,s=1; for(int i=3;i<=n;i++){ p=q; q=r; r=s; s=p+q+r; } return s; } }
Problem solution
- If the teponacci sequence follows the recursive method of Fibonacci sequence, it will lead to timeout.
- Therefore, this problem needs to be advanced dynamically. p is Tn, q represents Tn+1,r is Tn+2,s is Tn+3,Tn+3 = Tn + Tn+1 + Tn+2, and Tn\Tn+1\ Tn+2 are all changing recursively.
- The time complexity is O (n) and the space complexity is O(1).
2022-1-12
70. Climb stairs
Topics and examples
Suppose you are climbing stairs. You need n steps to reach the roof.
You can climb one or two steps at a time. How many different ways can you climb to the roof?
Note: given n is a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: there are two ways to climb to the roof.
- 1st order + 1st order
- Second order
Example 2:
Input: 3
Output: 3
Explanation: there are three ways to climb to the roof.
3. 1st order + 1st order + 1st order
4. 1st order + 2nd order
5. Order 2 + order 1
code
class Solution { public int climbStairs(int n) { int p=0,q=0,s=1; for(int i=1;i<=n;i++){ p=q; q=s; s=p+q; } return s; } }
Solution:
- When you go up three stairs and one step, you need to consider how to go to the next two steps; When you go up to level 2, you need to consider how to go to the next level. Push down, go up n stairs and go up 1 step. You need to consider how to go to the next (n-1) step; For the upper 2 orders, we need to consider how to go in the later (n-2) order.
- f(n)=f(n-1)+f(n-2) n>=3
- If f(n-1)+f(n-2) is returned directly, it will timeout; Use the for loop to find f(n)
- Time complexity: the loop is executed n times, O(n).
- Space complexity: O(1).
746. Use the minimum cost to climb stairs
Topics and examples
Give you an integer array cost, where cost[i] is the cost of climbing up the ith step of the stairs. Once you pay this fee, you can choose to climb up one or two steps.
You can choose to climb the stairs from the steps with subscript 0 or subscript 1.
Please calculate and return the minimum cost to reach the top of the stairs.
Example 1:
Input: cost = [10,15,20]
Output: 15
Explanation: you will start with a step with a subscript of 1.
- Pay 15 and climb two steps up to the top of the stairs.
The total cost is 15.
Example 2:
Input: cost = [1100,1,1,1100,1,1100,1]
Output: 6
Explanation: you will start with a step with a subscript of 0.
- Pay 1 and climb up two steps to the step with subscript 2.
- Pay 1 and climb up two steps to the step with subscript 4.
- Pay 1, climb two steps up to the step with subscript 6.
- Pay 1 and climb up one step to the step with subscript 7.
- Pay 1, climb two steps up to the step with subscript 9.
- Pay 1, climb one step up to the top of the stairs.
The total cost is 6.
Tips:
2 <= cost.length <= 1000
0 <= cost[i] <= 999
Code 1
class Solution { public int minCostClimbingStairs(int[] cost) { int n=cost.length; int []dp=new int[n+1]; dp[0]=0; dp[1]=0; for(int i=2;i<=n;i++){ dp[i]=Math.min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]); } return dp[n]; } }
Code 2 (optimization)
class Solution { public int minCostClimbingStairs(int[] cost) { int n=cost.length; int prev=0,curr=0; for(int i=2;i<=n;i++){ int next=Math.min(curr+cost[i-1],prev+cost[i-2]); prev=curr; curr=next; } return curr; } }
Problem solution
- dp array records need the least cost to register to the i-th step.
- After paying the fee, you can choose to climb up one or two steps,
- If you climb a step, dp[i-1]+cost[i-1];
- If you climb two steps, dp[i-2]+cost[i-2];
- Take the minimum value: DP [i] = math min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]);
- Code 2 is optimized and the space complexity is reduced. prev represents the previous value, curr represents the current value, and next represents the next value.
- Code 1: time complexity: O(n) space complexity: O(n)
- Code 2: time complexity: O(n) space complexity: O(1)
2022-1-13
198. House raiding
Topics and examples
You are a professional thief who plans to steal houses along the street. There is a certain amount of cash hidden in each room. The only restrictive factor affecting your theft is that the adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are intruded by thieves on the same night, the system will automatically alarm.
Given a non negative integer array representing the amount stored in each house, calculate the maximum amount you can steal overnight without touching the alarm device.
Example 1:
Input: [1,2,3,1]
Output: 4
Explanation: steal house 1 (amount = 1) and then steal house 3 (amount = 3).
Maximum amount stolen = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1]
Output: 12
Explanation: steal house 1 (amount = 2), steal house 3 (amount = 9), and then steal house 5 (amount = 1).
Maximum amount stolen = 2 + 9 + 1 = 12.
Tips:
1 <= nums.length <= 100
0 <= nums[i] <= 400
code:
class Solution { public int rob(int[] nums) { int n=nums.length; if(n==0){ return 0; } if(n==1){ return nums[0]; } int [] dp=new int[nums.length]; dp[0]=nums[0]; dp[1]=Math.max(nums[0],nums[1]); for(int i=2;i<n;i++){ dp[i]=Math.max(dp[i-1],dp[i-2]+nums[i]); } return dp[n-1]; } }
Solution:
- dp array records the maximum theft amount of house i
- If you steal room i, you cannot steal room i-1. The amount of theft is the maximum amount of the previous i-2 plus the amount of the current room
- If the i-th house is not stolen, the total amount of theft is the maximum total amount of the first i-1 house
- The time complexity is O (n), and the space complexity is O (n)
213. House raiding II
Topics and examples
You are a professional thief. You plan to steal houses along the street. There is a certain amount of cash in each room. All the houses in this place are in a circle, which means that the first house and the last house are next to each other. At the same time, adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are intruded by thieves on the same night, the system will automatically alarm.
Given a non negative integer array representing the amount stored in each house, calculate the maximum amount you can steal tonight without touching the alarm device.
Example 1:
Input: num = [2,3,2]
Output: 3
Explanation: you can't steal house 1 (amount = 2) and then house 3 (amount = 2) because they are adjacent.
Example 2:
Input: num = [1,2,3,1]
Output: 4
Explanation: you can steal house 1 (amount = 1) and then house 3 (amount = 3).
Maximum amount stolen = 1 + 3 = 4.
Example 3:
Input: num = [0]
Output: 0
Tips:
1 <= nums.length <= 100
0 <= nums[i] <= 1000
code
class Solution { public int rob(int[] nums) { int n=nums.length; if(n==0){ return 0; } if(n==1){ return nums[0]; } if(n==2){ return Math.max(nums[0],nums[1]); } return Math.max(robRange(0,n-2,nums),robRange(1,n-1,nums)); } public int robRange(int start,int end,int nums[]){ int first=nums[start]; int second=Math.max(nums[start],nums[start+1]); for(int i=start+2;i<=end;i++){ int tmp=Math.max(second,first+nums[i]); first=second; second=tmp; } return second; } }
Problem solution
- This question is similar to 198 The difference is that the last house is next to the first house. So if we choose the first one, we won't choose the last one, and if we choose the last one, we won't choose the first one.
- There are two kinds of intervals, one is [0, n-2], the other is [1, n-1].
- The time complexity is O(n), and the space complexity is O(1)
2022-1-14
740. Delete and gain points
Topics and examples
Give you an integer array nums, you can do some operations on it.
In each operation, select any num [i], delete it and obtain the number of num [i]. After that, you must delete all elements equal to nums[i] - 1 and nums[i] + 1.
You have 0 points at the beginning. Returns the maximum number of points you can get through these operations.
Example 1:
Input: num = [3,4,2]
Output: 6
Explanation:
Delete 4 to get 4 points, so 3 is also deleted.
After that, delete 2 and get 2 points. Get a total of 6 points.
Example 2:
Input: num = [2,2,3,3,3,4]
Output: 9
Explanation:
Delete 3 to get 3 points, and then delete two 2 and 4.
After that, delete 3 again to obtain 3 points, and delete 3 again to obtain 3 points.
Get a total of 9 points.
Tips:
1 <= nums.length <= 2 * 10^4
1 <= nums[i] <= 10^4
code:
class Solution { public int deleteAndEarn(int[] nums) { int max=0; for(int val:nums){ max=Math.max(max,val); } int []sum=new int[max+1]; for(int val:nums){ sum[val]+=val; } return rob(sum); } public int rob(int[] nums) { int first=nums[0]; int second=Math.max(nums[0],nums[1]); for(int i=2;i<nums.length;i++){ int tmp=second; second=Math.max(first+nums[i],second); first=tmp; } return second; } }
Solution:
- Find the maximum value of the num array, that is, the length of the sum array. The sum array stores the sum of the values of the corresponding numbers, and then carry out dynamic programming.
- Time complexity: O(N+M), where N is the length of array nums and M is the maximum value of elements in nums.
- Space complexity: O(M).
55. Jumping game
Topics and examples
Given a nonnegative integer array nums, you are initially at the first subscript of the array.
Each element in the array represents the maximum length you can jump at that position.
Judge whether you can reach the last subscript.
Example 1:
Input: num = [2,3,1,1,4]
Output: true
Explanation: you can jump 1 step first, from subscript 0 to subscript 1, and then jump 3 steps from subscript 1 to the last subscript.
Example 2:
Input: num = [3,2,1,0,4]
Output: false
Explanation: in any case, you will always reach the position with subscript 3. However, the maximum jump length of this subscript is 0, so it is never possible to reach the last subscript.
Tips:
1 <= nums.length <= 3 * 10^4
0 <= nums[i] <= 10^5
code:
class Solution { public boolean canJump(int[] nums) { int n=nums.length; int max=nums[0]; if(n==1){ return true; } for(int i=1;i<n;i++){ if(i<=max){ max=Math.max(max,i+nums[i]); if(max>=n-1){ return true; } } } return false; } }
Solution:
- Calculate the maximum interval at each step. The maximum interval is the maximum value of the sum of the previous maximum interval value and the values of the current subscript and the current subscript. If the maximum interval is greater than or equal to the subscript of the last value, it can be reached, otherwise it cannot be reached.
- The time complexity is O(n), and the space complexity is O(1)
45. Jumping game II
Topics and examples
Give you a non negative integer array nums, and you are initially in the first position of the array.
Each element in the array represents the maximum length you can jump at that position.
Your goal is to use the least number of jumps to reach the last position of the array.
Suppose you can always reach the last position of the array.
Example 1:
Input: num = [2,3,1,1,4]
Output: 2
Explanation: the minimum number of jumps to the last position is 2.
Jump from subscript 0 to subscript 1, step 1, and then step 3 to the last position of the array.
Example 2:
Input: num = [2,3,0,1,4]
Output: 2
Tips:
1 <= nums.length <= 104
0 <= nums[i] <= 1000
code:
class Solution { public int jump(int[] nums) { int p=nums.length-1; int count=0; while(p>0){ for(int i=0;i<p;i++){ if(i+nums[i]>=p){ p=i; count++; break; } } } return count; } }
Solution:
- and 55. Jumping game The difference is that the greedy strategy of this question is from back to front, find the farthest position that can reach the last value, and then push forward in turn.
- Two for loops with time complexity of O (n).
- Space complexity is O(1)
2022-1-17
53. Maximum subarray and
Topics and examples
Give you an integer array nums. Please find a continuous sub array with the largest sum (the sub array contains at least one element) and return its maximum sum.
A subarray is a contiguous part of an array.
Example 1:
Input: num = [- 2,1, - 3,4, - 1,2,1, - 5,4]
Output: 6
Explanation: the maximum sum of continuous subarray [4, - 1,2,1] is 6.
Example 2:
Input: num = [1]
Output: 1
Example 3:
Input: num = [5,4, - 1,7,8]
Output: 23
Tips:
1 <= nums.length <= 105
-104<= nums[i] <= 104
code:
class Solution { public int maxSubArray(int[] nums) { int []a=new int[nums.length+1]; a[0]=nums[0]; for(int i=1;i<nums.length;i++){ if(a[i-1]+nums[i]>nums[i]){ a[i]=a[i-1]+nums[i]; }else{ a[i]=nums[i]; } } int max=a[0]; for(int i=1;i<nums.length;i++){ if(a[i]>max){ max=a[i]; } } return max; } }
Solution:
- a array is used to store the maximum sum. If the sum of the previous sum and the corresponding value of the current num is greater than the corresponding value of the current num, that is, the sum of the previous sum is greater than 0, then the latter sum is equal to the sum of the previous sum plus the corresponding value of the current num, otherwise the latter sum is equal to the corresponding value of the current num.
- Then find the maximum value of array a, which is the maximum sum.
- The time complexity is O(n), and the space complexity is O(n)
2022-1-18
152. Product maximum subarray
Topics and examples
Give you an integer array nums. Please find the continuous sub array with the largest product in the array (the sub array contains at least one number) and return the product corresponding to the sub array.
Example 1:
Input: [2,3, - 2,4]
Output: 6
Explanation: subarray [2,3] has a maximum product of 6.
Example 2:
Input: [- 2,0, - 1]
Output: 0
Explanation: the result cannot be 2 because [- 2, - 1] is not a subarray.
code:
class Solution { public int maxProduct(int[] nums) { int max=nums[0],min=nums[0],ans=nums[0]; int n=nums.length; for(int i=1;i<n;i++){ int mx=max,mn=min; max=Math.max(mx*nums[i],Math.max(mn*nums[i],nums[i])); min=Math.min(mn*nums[i],Math.min(mx*nums[i],nums[i])); ans=Math.max(ans,max); } return ans; } }
Solution:
- The difference between this problem and the solution of continuous subarray of maximum sum is that there is no optimal substructure, and the local optimal solution cannot lead to the global optimal solution.
- Maximum product. The current value is a positive number. You want the previous product to be a larger positive number; The current value is negative. You want the previous product to be a smaller negative number. Therefore, the maximum value \ minimum value is selected between the maximum value multiplied by the current value, the minimum value multiplied by the current value and the current value.
- The time complexity is O (n), and the space complexity is O(1)
2022-1-19
1014. Best sightseeing combination
Topics and examples
Give you a positive integer array values, where values[i] represents the score of the ith scenic spot, and the distance between the two scenic spots I and j is j - i.
The score of the sightseeing combination composed of a pair of scenic spots (I < J) is values[i] + values[j] + i - j, that is, the sum of the scores of scenic spots minus the distance between them.
Return to a pair of tourist attractions can get the highest score.
Example 1:
Input: values = [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
Example 2:
Input: values = [1,2]
Output: 2
Tips:
2 <= values.length <= 5 * 104
1 <= values[i] <= 1000
code:
class Solution { public int maxScoreSightseeingPair(int[] values) { int n=values.length; int ans=0; int max=values[0]+0; for(int j=1;j<n;j++){ ans=Math.max(ans,max+values[j]-j); max=Math.max(max,values[j]+j); } return ans; } }
Solution:
- In dynamic programming, the maximum value is initialized to the value and subscript of the first number, and then the subscript is subtracted from the following value. The maximum value is updated to the current value and subscript.
- The time complexity is O(n), and the space complexity is O(1)
2022-1-20
309. The best time to buy and sell stocks includes the freezing period
Topics and examples
Given an array of integers, the ith element represents the stock price on day i.
Design an algorithm to calculate the maximum profit. You can complete as many transactions as possible (buying and selling a stock multiple times) under the following constraints:
You cannot participate in multiple transactions at the same time (you must sell the previous shares before buying again).
You can't buy the stock on the second day after the freeze period.
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: the corresponding transaction status is: [buy, sell, frozen period, buy, sell]
Code 1:
class Solution { public int maxProfit(int[] prices) { int n=prices.length; if(n==0){ return 0; } //f[i][0]: the maximum return of holding stocks //f[i][1]: do not hold stocks and are in the freezing period //f[i][3]: do not hold stocks and are not in the freezing period int [][]f=new int[n][3]; f[0][0]=-prices[0];//The return on holding shares is the negative value of the price of the purchased shares on the first day for(int i=1;i<n;i++){ //Holding stocks in hand: 1. Holding stocks the day before; 2. Not holding stocks and not in the freezing period Buy on the same day f[i][0]=Math.max(f[i-1][0],f[i-1][2]-prices[i]); //Do not hold stocks and are in the freezing period: 1. Sell on the same day and hold stocks the previous day to get the money to sell stocks on the same day f[i][1]=f[i-1][0]+prices[i]; //Do not hold stocks and are not in the freezing period: 1. Do not hold stocks the day before and are not in the freezing period; 2. Do not hold stocks the day before and are in the freezing period f[i][2]=Math.max(f[i-1][2],f[i-1][1]); } //There is no point in not selling the stock on the last day return Math.max(f[n-1][1],f[n-1][2]); } }
Code 2 (space optimization):
Solution:
- Analyze the three cases, and then take the maximum value of each case. Finally, take the maximum value of the latter two cases.
- Code 1: time complexity is O(n), space complexity is O(n)
- Code 2: time complexity is O(n), space complexity is O (1)
2022-1-21
139. Word splitting*
Topics and examples
Give you a string s and a string list wordDict as a dictionary. Please judge whether you can use the words in the dictionary to splice s.
Note: it is not required to use all the words in the dictionary, and the words in the dictionary can be reused.
Example 1:
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: return true because "leetcode" can be spliced by "leet" and "code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: return true because "applepenapple" can be spliced by "apple", "pen" and "apple".
Note that you can reuse words in the dictionary.
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
Tips:
1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s and wordDict[i] are only composed of lowercase English letters
All strings in wordDict are different from each other
code:
class Solution { public boolean wordBreak(String s, List<String> wordDict) { Set<String> wordDictSet=new HashSet(wordDict); boolean []dp=new boolean[s.length()+1]; dp[0]=true; for(int i=1;i<=s.length();i++){ for(int j=0;j<i;j++){ if(dp[j]&&wordDictSet.contains(s.substring(j,i))){ dp[i]=true; break; } } } return dp[s.length()]; } }
Solution:
- I don't quite understand. The time complexity is O (n2) and the space complexity is O(n)
2022-1-22
413. Division of arithmetic sequence
tim
If a sequence has at least three elements and the difference between any two adjacent elements is the same, the sequence is called equal difference sequence.
For example, [1,3,5,7,9], [7,7,7] and [3, - 1, - 5, - 9] are equal difference sequences.
Give you an integer array nums and return the number of subarrays in the array nums that are all equal difference arrays.
A subarray is a continuous sequence in an array.
Example 1:
Input: num = [1,2,3,4]
Output: 3
Explanation: there are three sub arithmetic arrays in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.
Example 2:
Input: num = [1]
Output: 0
Tips:
1 <= nums.length <= 5000
-1000 <= nums[i] <= 1000
error code
class Solution { public int numberOfArithmeticSlices(int[] nums) { int n=nums.length; int total=0; if(n<3){ return 0; } Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<n-1;i++){ map.put(nums[i+1]-nums[i],map.getOrDefault(nums[i+1]-nums[i],0)+1); } for(Map.Entry<Integer,Integer> entry:map.entrySet()){ int num=entry.getValue(); total+=jie(num-1); System.out.println(num); } return total; } public int jie(int num){ // if(num==1){ // return 1; // } // return num+jie(num-1); int total=0; for(int i=1;i<=num;i++){ total+=num; } return total; } }
Correct code:
class Solution { public int numberOfArithmeticSlices(int[] nums) { int n=nums.length; int total=0; if(n<3){ return total; } int d=nums[0]-nums[1]; int t=0; for(int i=2;i<n;i++){ if(nums[i-1]-nums[i]==d){ ++t; }else{ d=nums[i-1]-nums[i]; t=0; } total+=t; } return total; } }
Solution:
- The error code is wrong because it does not consider that the difference between the front isochronous sequence and the rear isochronous sequence is the same, but it is disconnected in the middle, so the idea is wrong.
- Correct code, because the subarray must have three or more, so the subscript starts with 2.
- If it is equal to the difference, add one. If it is not equal, the new value is equal to the difference and the increment is 0. Recalculate.
- The time complexity is O (n), and the space complexity is O(1)