Data structure and algorithm
sort
Merge sort (divide and conquer algorithm)
The idea is to recursively split the array, compare and replace it, and then merge it
Code implementation:
package com.xu.fingeroffer.recursion; import java.util.Arrays; public class Merge sort { public static void main(String[] args) { int a[] = {9, 2, 6, 3, 5, 7, 10, 11, 12}; int[] sort = sort(a); System.out.println(Arrays.toString(sort)); } static int[] sort(int[] array) { if (array.length != 0) { divide(array, 0, array.length - 1); } return array; } private static void divide(int[] array, int start, int end) { if (start >= end) { return; } int mid = (end+start)/ 2; divide(array, start, mid);//Left recursion divide(array, mid + 1, end);//Right recursion memerg(array, start, mid, end);//Merge two child columns } private static void memerg(int[] array, int start, int mid, int end) { int[] temp = new int[end - start + 1]; int p1 = start; int p2 = mid + 1; int k = 0; while (p1 <= mid && p2 <= end) { if (array[p1] < array[p2]) { temp[k++] = array[p1++]; } else { temp[k++] = array[p2++]; } } while (p1 <= mid) { temp[k++] = array[p1++]; } while (p2 <= end) { temp[k++] = array[p2++]; } for (int i = 0; i < temp.length; i++) { array[i + start] = temp[i]; } } }
Sword finger offer
1-10
10. Rectangular overlay
Problem Description:
We can use the small rectangle of 21 to cover the larger rectangle horizontally or vertically. How many different methods are there to cover a 2*n large rectangle with n 21 small rectangles without overlap from the same direction?
For example, when n=3, 2 * 3 rectangular blocks have three different covering methods (from the same direction):
Problem resolution:
When n=1, the value is 1. When n=2, there are two solutions. When n=3, there are three solutions. When n=4, it is f2+f3. This is a Fibonacci sequence problem
Code implementation:
package com.xu.fingeroffer.ten; public class Rectangular overlay 10 { public int rectCover(int target) { if (target==0||target == 1 || target == 2 || target == 3) { return target; } int f1 = 2; int f2 = 3; for (int i = 4; i <= target; i++) { int num = f1; f1 = f2; f2 = f1+num; } return f2; } }
11-20
13. Adjust the array order so that odd numbers precede even numbers
Problem description
Input an integer array, and implement a function to adjust the order of numbers in the array, so that all odd numbers are in the first half of the array and all even numbers are in the second half of the array, and ensure that the relative positions between odd numbers and odd numbers, even numbers and even numbers remain unchanged.
Problem analysis
Use two arrays to traverse the array, put the odd number into the 1 array and the even number into the 2 array, and finally connect the 1 and 2 arrays
code implementation
package com.xu.fingeroffer.twenty; import java.util.LinkedList; public class Adjust the array order so that the odd number precedes the even number 13 { /** * queue * @param array * @return */ public int[] reOrderArray (int[] array) { LinkedList<Integer> l1 = new LinkedList<>(); LinkedList<Integer> l2 = new LinkedList<>(); for (int i = 0; i < array.length; i++) { if(array[i]%2==1){ l1.add(array[i]); }else { l2.add(array[i]); } } l1.addAll(l2); int []result = new int [array.length]; for (int i = 0; i < array.length; i++) { result[i]=l1.removeFirst(); } return result; } /** * array */ public int[] reOrderArray1 (int[] array) { int []a = new int [array.length]; int []b = new int [array.length]; int j = 0; int k = 0; for (int i = 0; i < array.length; i++) { if(array[i]%2==1){ a[j] = array[i]; j++; }else { b[k]=array[i]; k++; } } for (int i = 0; i < k ;i++) { a[j]=b[i]; j++; } return a; } }
14. The last k nodes in the linked list
Title Description
Input a linked list and output a linked list. The output linked list contains all nodes from the penultimate node to the tail node in the original linked list.
If the length of the linked list is less than k, please return a linked list with a length of 0.
Problem analysis
Set a flag bit index and traverse one node at a time. The flag bit is + 1. If k > index, return null. Traverse K and the final output result should be the node pull ed from the stack
code implementation
package com.xu.fingeroffer.twenty; import com.xu.fingeroffer.node.ListNode; import java.util.HashMap; import java.util.Stack; public class Last to last in the linked list k Nodes 14 { public static void main(String[] args) { ListNode node = new ListNode(1); node.next = new ListNode(2); node.next.next= new ListNode(3); ListNode listNode = FindKthToTail(node, 1); } public static ListNode FindKthToTail (ListNode pHead, int k) { int index = 0; // write code here if(k==0||pHead==null){ return null; } // write code here Stack<ListNode> stack = new Stack<>(); while (pHead!=null){ stack.push(pHead); index++; pHead=pHead.next; } if(index<k) return null; for (int i = 1; i < k; i++) { stack.pop(); } return stack.pop(); } }
15. Reverse linked list
Problem description
Enter a linked list. After reversing the linked list, output the header of the new linked list.
Topic analysis
Put all the data in the linked list into a list set, and use the header interpolation method to finally get the inverted linked list
code implementation
package com.xu.fingeroffer.twenty; import com.xu.fingeroffer.node.ListNode; public class Reverse linked list 15 { public ListNode ReverseList(ListNode head) { if(head==null||head.next==null){ return head; } ListNode first = null; while (head!=null){ ListNode second = head; head=head.next; second.next=first; first=second; } return first; } }
16. Merge two sorted linked lists
Problem description
Input two monotonically increasing linked lists and output the combined linked list. Of course, we need the combined linked list to meet the monotonic non decreasing rule.
Topic analysis
Through two linked lists: build a new linked list head(Interger.MIN) cur = head, and then traverse and compare the two linked lists. Put the smaller value into cur. If one traverses, point the next pointer of cur to the other linked list
code implementation
package com.xu.fingeroffer.twenty; import com.xu.fingeroffer.listnode.ListNode; /** * Topic analysis: * Create a new linked list * The values of the two linked lists are compared and small ones are inserted into the next node of the new linked list */ public class Merge two sorted linked lists { public ListNode Merge(ListNode list1, ListNode list2) { //Make a judgment. If both are empty, return null directly //If one of the two is not empty, the non empty one is returned if (list1 == null) { if (list2 != null) return list2; else return null; } if (list2 == null) { if (list1 != null) { return list1; } } //Create a new linked list ListNode head = new ListNode(Integer.MIN_VALUE); ListNode cur = head; //Start comparing two arrays while (list1 != null && list2 != null) { //Make a judgment and put the small ones into the cur linked list if (list1.val < list2.val) { cur.next = list1; cur = cur.next;//Pointer backward list1 = list1.next; } else { cur.next = list2; cur = cur.next; list2 = list2.next; } } //If one linked list is traversed and the other is not traversed if (list1 != null) { cur.next = list1; } else { cur.next = list2; } return head.next; } }
18. Binary tree image:
Problem Description:
Build a mirror binary tree for a binary tree
For example: Source binary tree 8 / \ 6 10 / \ / \ 5 7 9 11 Mirror binary tree 8 / \ 10 6 / \ / \ 11 9 7 5
Input:
{8,6,10,5,7,9,11}
copy
Return value:
{8,10,6,11,9,7,5}
Problem resolution:
Recursive call to perform replacement: if there are left and right child nodes, replace the left and right child nodes,
And implement the mirroring method for the left and right child nodes
code implementation
package com.xu.fingeroffer.twenty; import com.xu.fingeroffer.node.TreeNode; /** * Operate the given binary tree to make it a mirror of the source binary tree */ public class Image of binary tree 18 { /** * Problem analysis: use recursion to replace two child nodes if the next of the binary tree is not null */ public TreeNode Mirror(TreeNode pRoot) { // write code here if (pRoot == null) { return null; } else rootMirror(pRoot); return pRoot; } public void rootMirror(TreeNode pRoot) { //If it is not null, replace the two child nodes of the binary tree if (pRoot != null) { TreeNode temp = pRoot.left; pRoot.left = pRoot.right; pRoot.right = temp; } //If the left child node is not null, the recursive downward traversal performs the replacement if (pRoot.left != null) { rootMirror(pRoot.left); } //If the right child node is not null, the recursive downward traversal performs the replacement if (pRoot.right != null) { rootMirror(pRoot.right); } } }
20. Stack containing min function
Problem description
To define the data structure of the stack, please implement a min function in this type that can get the smallest element in the stack, and the time complexity of calling min function, push function and pop function is O(1)
push(value): push value into the stack
pop(): pop up stack top element
top(): get stack top element
min(): get the smallest element in the stack
Example:
Input: [PSH-1 "," PSH2 "," MIN "," TOP "," POP "," PSH1 "," TOP "," MIN "]
Output: - 1,2,1, - 1
Resolution:
"PSH-1" means to push - 1 into the stack, and the element in the stack is - 1
"PSH2" means to push 2 into the stack, and the elements in the stack are 2, - 1
"MIN" means to get the smallest element in the stack = = > Return - 1
"TOP" means to get the stack TOP element = = > return 2
"POP" means POP the top element of the stack, POP 2, and the element in the stack is - 1
"PSH-1" means to push 1 into the stack, and the elements in the stack are 1, - 1
"TOP" means to get the stack TOP element = = > Return 1
"MIN" means to get the smallest element in the stack = = > Return - 1
Topic analysis
Build a stack
20-30
21: push in pop-up sequence of stack
Title Description:
Enter two integer sequences, the first is the pressing sequence and the second is the pop-up sequence. Assuming that all numbers are unequal, judge whether the second is the first pop-up sequence
Problem analysis
* Topic analysis: * add to b Flag bit index * Add an auxiliary stack to a Array traversal is pushed onto the stack * Determine whether the stack top element is equal to b If the elements in the array subscript are equal, the top element of the stack will pop up, index Plus one, if the stack is null Or unequal, the next cycle is carried out
code implementation
package com.xu.fingeroffer.thirty; import java.util.Stack; /** * Title Description: * Enter two integer sequences, the first is the pressing sequence and the second is the pop-up sequence. Assuming that all numbers are unequal, judge whether the second is the first pop-up sequence */ public class Stack push pop sequence 21 { public static void main(String[] args) { int[] a = {1, 2, 3, 4, 5}; int[] b = {5, 4, 3, 2, 1}; System.out.println(Solution(a, b)); } /** * Topic analysis: * Add b flag bit index * Add an auxiliary stack and push the a array traversal into the stack * Judge whether the top element of the stack is equal to the element of the array subscript in b. if it is equal, the top element of the stack will pop up, and the index will be added by one. If the stack is null or unequal, the next cycle will be carried out */ public static boolean Solution(int[] a, int[] b) { if (a.length != b.length) { return false; } int index = 0; Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < a.length; i++) { //Add elements from a to the stack stack.push(a[i]); //Determine whether the element in the stack is null or whether the subscript position of the b array is equal to the top element of the stack while (!stack.isEmpty() && stack.peek() == b[index]) { stack.pop(); index++; } } return stack.isEmpty(); } }
28: more than half of the numbers in the array
Title Description
A number in the array appears more than half the length of the array. Please find out this number. For example, enter an array of length 9 [1,2,3,2,2,2,5,4,2]. Since the number 2 appears five times in the array, more than half the length of the array, 2 is output. You can assume that the array is non empty and that there are always many elements in a given array. 1 < = array length < = 50000
problem analysis
Save the array traversal in a map, judge the value in the map, and return if one of the values is greater than half the length of the array
code implementation
package com.xu.fingeroffer.thirty; import java.util.HashMap; /** * A number in the array appears more than half the length of the array. Please find out this number. For example, enter an array of length 9 [1,2,3,2,2,2,5,4,2]. Since the number 2 appears five times in the array, more than half the length of the array, 2 is output. You can assume that the array is non empty and that there are always many elements in a given array. 1 < = array length < = 50000 */ public class More than half of the numbers in the array { public static int MoreThanHalfNum_Solution(int [] array) { if(array.length==0){ return 0; } HashMap<Integer, Integer> map = new HashMap<>(); for (int i : array) { if(map.containsKey(i)){ map.put(i,map.get(i)+1); }else { map.put(i,1); } if(map.get(i)>array.length/2){ return i; } } return 0; } }
29: minimum k number
Title Description:
Given an array, find the smallest number of K. For example, if the array elements are 8 numbers 4,5,1,6,2,7,3,8, the smallest 4 numbers are 1,2,3,4.
- 0 <= k <= input.length <= 10000
- 0 <= input[i] <= 10000
Problem analysis
Sort the array and add it to the collection
code implementation
package com.xu.fingeroffer.thirty; import java.util.ArrayList; import java.util.Arrays; /** * Given an array, find the smallest number of K. For example, if the array elements are 8 numbers 4,5,1,6,2,7,3,8, the smallest 4 numbers are 1,2,3,4. * 0 <= k <= input.length <= 10000 * 0 <= input[i] <= 10000 */ public class least k Number 29 { public static void main(String[] args) { int[] a = {0, 1, 2, 1, 2}; System.out.println(Arrays.toString(GetLeastNumbers_Solution(a, 3).toArray())); System.out.println(Arrays.toString(a)); } public static ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < input.length; i++) { for (int j = input.length - 1; j > i; j--) { if (input[i] > input[j]) { int temp; temp = input[i]; input[i] = input[j]; input[j] = temp; } } } for (int i = 0; i < k; i++) { list.add(input[i]); } return list; } }
30: maximum sum of consecutive subarrays
Title Description
Enter an integer array with both positive and negative numbers. One or more consecutive integers in the array form a sub array. Find the maximum value of the sum of all subarrays. The required time complexity is O(n)
Problem analysis
Traverse the array and set a max value and variable value. The variable value is added from front to back. If the array is null, max = 0. Traverse once. If the variable value is > max, assign the variable value to max. if the variable value is less than 0, assign a new value to the variable
code implementation
package com.xu.fingeroffer.thirty; import java.util.Arrays; import java.util.LinkedList; import java.util.ListIterator; /** * Give an array and find the maximum value of the sub array of the array */ public class Maximum sum of consecutive subarrays 30 { public static void main(String[] args) { int[] a = {1,-2,3,10,-4,7,2,-5}; System.out.println(FindGreatestSumOfSubArray(a)); } public static int FindGreatestSumOfSubArray(int[] array) { if (array.length == 0) { return 0; } LinkedList<Integer> list = new LinkedList<>(); int temp = 0; int max = array[0]; for (int i = 0; i < array.length; i++) { temp = temp + array[i]; list.add(array[i]); if (max < temp) { max = temp; } if (temp < 0) { temp = 0; list.clear(); } } System.out.println(Arrays.toString(list.toArray())); return max; } }
30-40
31: number of words in integer 1
Problem description
Enter an integer n and find the number of occurrences of 1 in the decimal representation of N integers 1 ~ n
For example, 1, 10, 11, 12 and 13 contain 1 in 1 ~ 13, so there are 6 in total
Topic analysis
Traverse from beginning to end if the number% 10 > 0 sum + 1 if the last bit is 1 sum+1
code implementation
34: the first character that appears only once
Problem description
Find the first character that appears only once in a string (0 < = string length < = 10000, all composed of letters), and return its position. If not, return - 1 (case sensitive). (count from 0)
Topic analysis
Traverse the string and put it into the map set. If there is a repetition, value+1, then traverse the string and take the subscript position where the first value is 1
code implementation
package com.xu.fingeroffer.forty; import java.util.HashMap; /** * Find the first character that appears only once in a string (0 < = string length < = 10000, all composed of letters), and return its position. If not, return - 1 (case sensitive). (count from 0) */ public class The first character that appears only once 34 { public static void main(String[] args) { System.out.println(FirstNotRepeatingChar("google")); } public static int FirstNotRepeatingChar(String str) { if (str==null||str.length()==0){ return -1; } int index=-1; HashMap<Character, Integer> map = new HashMap<>(); for (int i = 0; i < str.length(); i++) { if(map.get(str.charAt(i))==null){ map.put(str.charAt(i),1); }else { map.put(str.charAt(i),map.get(str.charAt(i))+1); } } for (int i = 0; i < str.length(); i++) { if (map.get(str.charAt(i))==1){ index = i; return index; } } return index; } }
36: the first common node of two linked lists
Problem Description:
Enter two acyclic single linked lists and find their first common node. (note that because the incoming data is a linked list, the prompt of error test data is displayed in other ways to ensure that the incoming data is correct)
Topic analysis:
For two acyclic single linked lists, find the common number in the two linked list sets, and traverse the two linked lists
Code implementation:
package com.xu.fingeroffer.forty; import com.xu.fingeroffer.node.ListNode; /** * Enter two acyclic single linked lists and find their first common node. (note that because the incoming data is a linked list, the prompt of error test data is displayed in other ways to ensure that the incoming data is correct) */ public class The first common node 36 of the two linked lists { //Solution 1 public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { if(pHead1==null||pHead2==null){ return null; } ListNode p1 = pHead1; ListNode p2 = pHead2; while (p1 != p2) { p1 = p1.next; p2 = p2.next; if (p1 == p2) { return p1; } if (p1 == null) { p1 = pHead1; } if (p2 == null) { p2 = pHead2; } } return p1; } /** * Solution 2 * @param pHead1 * @param pHead2 * @return */ public ListNode FindFirstCommonNode2(ListNode pHead1, ListNode pHead2) { if(pHead1==null||pHead2==null){ return null; } ListNode p1 = pHead1; ListNode p2 = pHead2; while (p1!=p2){ p1=p1.next; if(p1==p2){ return p1; } if(p1==null){ p1=pHead1; p2=p2.next; } } return p1; } }
38: depth of binary tree
Title Description
Enter a binary tree and find the depth of the tree. The nodes (including root and leaf nodes) passing from root node to leaf node form a path of the tree, and the length of the longest path is the depth of the tree.
problem analysis
Recursively compare the depth of the left and right child nodes
code implementation
package com.xu.fingeroffer.forty; import com.xu.fingeroffer.node.TreeNode; public class Depth of binary tree 38 { public int TreeDepth(TreeNode root) { if(root==null){ return 0; } return Math.max(TreeDepth(root.left),TreeDepth(root.right))+1; } }
39 balanced binary tree
Problem Description:
Enter a binary tree to judge whether the binary tree is a balanced binary tree.
Here, we only need to consider its balance, not whether it is a sorted binary tree
Balanced Binary Tree has the following properties: it is an empty tree or the absolute value of the height difference between its left and right subtrees does not exceed 1, and both the left and right subtrees are a Balanced Binary Tree.
Note: we agree that an empty tree is a balanced binary tree.
Topic analysis:
Calculate the maximum depth of the left and right sub nodes of the binary tree, and then compare them. If the difference is less than 1, continue to compare its sub trees until all are balanced binary trees
Code implementation:
package com.xu.fingeroffer.forty; import com.xu.fingeroffer.node.TreeNode; public class Depth of binary tree 38 { public int TreeDepth(TreeNode root) { if(root==null){ return 0; } return Math.max(TreeDepth(root.left),TreeDepth(root.right))+1; } }
40-50
45: Poker shunzi
Problem Description:
Now there are two pairs of playing cards, five playing cards at random from the playing cards. We need to judge whether shunzi is right or not.
There are the following rules:
\1. A is 1, J is 11, Q is 12, K is 13, and a cannot be regarded as 14
\2. Big and small Wang are 0, and 0 can be regarded as any card
\3. If the given five cards can form a shunzi (that is, the five cards are continuous), it will output true, otherwise it will output false.
For example, give the data [6,0,2,0,4]
The two zeros in the middle are regarded as 3 and 5. Namely: [6,3,2,5,4]
In this way, the five cards are continuous in the [2,6] interval and output true
The data guarantees that there are 5 numbers in each group, and each group contains at most 4 zeros. The number value of the array is [0, 13]
Problem analysis:
Sort the array, with the initial assignment num = 0; Then traverse. If it is 0, it will jump out of this cycle and enter the next cycle. If array[i]=array[i+1] returns false, otherwise
num= num+array[i+1]-array[i]; Finally, judge the value of num. as long as the value of num is less than 4, it will be returned as true, otherwise it will be false
code implementation
package com.xu.fingeroffer.fifry; import java.util.Arrays; public class Poker shunzi { public boolean IsContinuous(int[] numbers) { //Sort the passed in array Arrays.sort(numbers); int num = 0; //Traversal array for (int i = 0; i < numbers.length-1; i++) { //If 0, jump out of the loop if (numbers[i] == 0) { continue; } //If there is a duplicate number, false is returned else if (numbers[i] == numbers[i + 1]) { return false; } else { num = num + (numbers[i + 1] - numbers[i]); } } if (num <= 4) { return true; } else { return false; } } }
48: addition without addition, subtraction, multiplication and division
Title Description
Write a function and find the sum of two integers. It is required that the four operation symbols +, -, *, / shall not be used in the function body.
Problem analysis
Using bit operations, XOR shifts left
code implementation
package com.xu.fingeroffer.fifry; public class Bit operation plus 48 { public int Add(int num1,int num2) { while (num2!=0){ int temp = num1^num2; num2 = (num1&num2)<<1; num1 = temp; } return num1; } }
50: duplicate number in array
Title Description
describe
All numbers in an array of length n are in the range of 0 to n-1. Some numbers in the array are repeated, but I don't know how many numbers are repeated. I don't know how many times each number is repeated. Please find any duplicate number in the array. For example, if you input an array of length 7 [2,3,1,0,2,5,3], the corresponding output is 2 or 3. If there is illegal input, output - 1
Problem analysis
As you can see, the number size in the array will not exceed the length of the array, so you can use the array to create an empty array with the same length as the original array and pass through the epoch array, so that the value of the subscript position corresponding to the value of the original array in the new array is + 1; When the corresponding value in the following table is 2, this value is returned. If not, - 1 is returned
code implementation
package com.xu.fingeroffer.fifty; import java.util.HashMap; public class Duplicate array in array 50 { public static void main(String[] args) { int []a = {2,1,3,1,4}; System.out.println(duplicate2(a)); } public static int duplicate (int[] numbers) { if(numbers==null||numbers.length==0){ return -1; } // write code here HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < numbers.length; i++) { if(map.get(numbers[i])==null){ map.put(numbers[i],1); }else { return numbers[i]; } } return -1; } /** * Solution II * @param numbers * @return */ public static int duplicate2 (int[] numbers) { int []test = new int [numbers.length]; for (int i = 0; i < numbers.length; i++) { test[numbers[i]]++; if(test[numbers[i]]==2){ return numbers[i]; } } return -1; } }