Primary algorithm
1, Remove duplicates from sort array
Title: give you an ordered array nums. Please delete the repeated elements in place, so that each element appears only once, and return the new length of the deleted array.
Do not use additional array space. You must modify the input array in place and complete it with O(1) additional space.
Example 1: Input: nums = [1,1,2] Output: 2, nums = [1,2]
Explanation: the function should return a new length of 2, and the first two elements of the original array num are modified to 1 and 2. There is no need to consider the elements in the array that exceed the new length.
/** * count Number of record element repetitions = = number of steps the array element moves forward */ public int removeDuplicates(int[] nums) { int count = 0; for (int i = 1; i < nums.length; i++) { if(nums[i] == nums[i - 1]){ count ++; }else { nums[i - count] = nums[i]; } } return nums.length - count; }
2, The best time to buy and sell stocks
Given an array of prices, where {prices[i] is the price of a given stock on day I.
Design an algorithm to calculate the maximum profit you can make. You can complete as many transactions as possible (buying and selling a stock multiple times).
Example: input: prices = [7,1,5,3,6,4] output: 7
Explanation: if you buy on the second day (stock price = 1) and sell on the third day (stock price = 5), this exchange can make a profit = 5-1 = 4.
Then, buy on the 4th day (stock price = 3) and sell on the 5th day (stock price = 6). This exchange can make a profit = 6-3 = 3
Solution 1:
public static int maxProfit(int[] prices) { int money = 0; if(prices == null || prices.length < 2){ return 0; } boolean a = true; //The flag bit records the change of increasing and decreasing for (int i = 0; i < prices.length - 1; i++) { if(prices[i] >= prices[i + 1] && !a){ money = money + prices[i]; a = true; } if(prices[i] < prices[i + 1] && a){ money = money - prices[i]; a = false; } } //The last judgment is increasing or decreasing, and increasing returns if(prices[prices.length - 1] > prices[prices.length - 2]){ money = money + prices[prices.length - 1]; } return money; }
3, Rotate array
Problem: the elements in the array rotate K positions to the right, where k is a non negative number
Case 1: int[] array = {1,2,3,4,5,6,7,8,9,10}; k Rotation digit k = 3 Output:[8,9,10,1,2,3,4,5,6,7]
public static int[] xuanZhuan(int[] array,int k){ int[] temp = array.clone(); for (int i = 0; i < array.length; i++) { int a = (i + k) % array.length; array[a] = temp[i]; } return array; }
4, There are duplicate elements
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. Returns false if each element in the array is different.
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
Solution 1: Violence
public static boolean method(int[] array){ if(array == null){ return true; } for (int i = 0; i < array.length; i++) { for (int j = i + 1; j < array.length; j++) { if(array[j] == array[i]){ return true; } } } return false; }
Solution 2:
Using set set property
There cannot be duplicate elements in set. Adding the same element failed
public static boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<>(); for (int num : nums) { if (!set.add(num)) return true; } return false; }
Solution 3:
Sort first and then compare whether the elements before and after are consistent
public static boolean containsDuplicate(int[] nums) { Arrays.sort(nums); for(int i = 0; i < nums.length - 1; i++) { if (nums[i] == nums[i + 1]) { return true; } } return false; }
5, A number that appears 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.
Example: input: [4,1,2,1,2] output: 4
Idea: use XOR operation to XOR all values
public int singleNumber(int[] nums) { int reduce = 0; for (int num : nums) { reduce = reduce ^ num; } return reduce; }
6, Intersection of two arrays
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 occurrence times are inconsistent, consider taking the smaller value). The order of output results can be ignored.
Example: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output:[2,2]
Idea: sort the two arrays before judging
public static int[] intersect(int[] nums1, int[] nums2) { Arrays.sort(nums1); Arrays.sort(nums2); ArrayList<Integer> list = new ArrayList<>(); int i = 0,j = 0; while (i < nums1.length && j <nums2.length) { if(nums1[i] < nums2[j]){ i ++; }else if(nums1[i] > nums2[j]){ j ++; }else { list.add(nums1[i]); i ++; j ++; } } int[] target = new int[list.size()]; for (int z = 0; z < list.size(); z++) { target[z] = list.get(z); } return target; }
7, Plus one
Given a non negative integer represented by a non empty array of integers, add one to the number.
The highest digit is stored in the first place of the array, and each element in the array stores only a single digit.
You can assume that this integer does not start with zero except the integer 0.
Example: Input: digits = [1,2,3] Output:[1,2,4] Explanation: the input array represents the number 123. All elements of the array are treated as a number: 123 + 1 = 124 9 + 1 = 10 99 + 1 = 100 235 + 1 = 236
solve:
public static int[] plusOne(int[] digits) { //Find the last element that is 9 for operation if(digits[digits.length - 1] == 9){ for (int i = digits.length - 1; i >= 0; i--) { if(digits[i] == 9){ //If the element is 9, the current element is set to 0 digits[i] = 0; }else { //It can be returned as long as one element in the period is not 9 digits[i] ++; return digits; } } int[] temp = new int[digits.length + 1]; temp[0] = 1; return temp; } //If the last element is not 9, it is directly++ digits[digits.length - 1] ++; return digits; }
8, Move zero
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]
Solution 1:
public static void moveZeroes(int[] nums) { //Number of occurrences of record 0 int pos = 0; for (int i = 0; i < nums.length; i++) { if(nums[i] == 0){ pos ++; }else if(pos > 0){ //Move element forward nums[i - pos] = nums[i]; } } if(pos > 0){ //The last element is set to 0 for (int i = 1; i <= pos; i++) { nums[nums.length - i] = 0; } } }
Solution 2:
public static void moveZeroes2(int[] nums) { int pos = 0; //Non-0 elements move forward for (int i = 0; i < nums.length; i++) { if(nums[i] != 0){ nums[pos ++] = nums[i]; } } //The last num.length - pos elements are set to 0 while(pos < nums.length){ nums [pos++] = 0; } }
9, Sum of two numbers
Given an integer array num , and an integer target value target, please find the two , integers whose sum is 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 be repeated in the answer.
You can return answers in any order.
Example 1: Input: nums = [2,7,11,15], target = 9 Output:[0,1] Explanation: because nums[0] + nums[1] == 9 ,return [0, 1] .
Solution 1: violence algorithm
//Violence algorithm public static int[] twoSum(int[] nums, int target){ for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if(nums[i] + nums[j] == target){ return new int[]{i,j}; } } } return new int[]{-1,-1}; }
Solution 2: HashMap
Idea:
Create a new HashMap storage element
Storage method: key (storage element value): nums[i], value (storage array subscript): I
Judgment condition m.get (target - num s [i])= Null, where target - num [i] is the second element value matching it. If the corresponding key can be found in the HashMap, it indicates that the sum of the two elements is equal to target, and the array subscript of the corresponding element can also be obtained.
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> m = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (m.get(target - nums[i]) != null) { return new int[]{m.get(target - nums[i]), i}; } m.put(nums[i], i); } return new int[]{0, 0}; }
10, Effective Sudoku
Please judge whether a Sudoku of {9 x 9 is effective. You only need to verify whether the filled numbers are valid according to the following 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 Indicates.
Example 1: Input: char[][] 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
Solution 1: violent solution
Idea:
- The three two-dimensional tables line col box are used to record the positions occupied by elements
- The line table can be regarded as the original board [] [] character array table
- col table rows can be treated as columns in the line table
- The row of the box table can be regarded as the 3x3 cell of the original board [] [] character array (the 9x9 grid is divided into 9 3x3 cells, arranged in order from left to right)
- Cells are represented as follows:
- pos0,pos1,pos2,
- pos3,pos4,pos5,
- pos6,pos7,pos8
- The three table elements are sorted in the table according to the specified sorting rules
- That is, the sorting position of the same element is fixed
- For example, there are two identical elements [, 9,3,4,6,8,9] in the first line of the board[0] [] character array
- It can be seen that the above has the same element 9, that is, board[0][1] = 9, board[0][8] = 9
- According to the sorting rule int pos = board[i][j] - '1';
- pos = board[0][1] - '1' = 8
- pos = board[0][8]- '1' = 8
- The obtained pos is equal to 8, so when the first position is not occupied, the element of board[0][1] occupies the position,
- When board[0][8] is executed, it is found that the location has been occupied, so this is an invalid Sudoku
public static boolean isValidSudoku(char[][] board){ //A two-dimensional array that stores rows int[][] line = new int[board.length][board[0].length]; //A two-dimensional array that stores columns int[][] col = new int[board.length][board[0].length]; //Two dimensional array of storage units int[][] box = new int[board.length][board[0].length]; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { //'.' in board two-dimensional character array Indicates that there are no elements, so you can skip directly if(board[i][j] == '.')continue; //The array subscript is 0-8, so pos represents the position of the sorted elements //Board [i] [J] - the range of '1' is [0-8] (you can view the corresponding value of ASCII table if you don't understand it), which corresponds to the sorted array subscript int pos = board[i][j] - '1'; //First, divide the 9x9 grid into 9 3x3 cells and sort them from left to right //boxIndex represents the position of cells from left to right, and the range of boxIndex is [0,8] int boxIndex = i/3 * 3 + j/3; //Judge whether the position in the two-dimensional array has been occupied (the value of no element in the two-dimensional array is 0 by default) if((line[i][pos] != 0) || (col[j][pos] != 0) || (box[boxIndex][pos] != 0))return false; //If the position is not occupied, a fixed value of 1 can be set, indicating that the position has been occupied line[i][pos] = col[j][pos] = box[boxIndex][pos] = 1; } } return true; }
11, 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:[[7,4,1],[8,5,2],[9,6,3]]
Solution 1:
Idea: first, exchange the two-dimensional matrix symmetrically up and down, and then exchange it diagonally
123 789 741 456 Symmetric exchange---> 456 Diagonal exchange---> 852 789 123 963
public static void rotate(int[][] matrix) { //Change position up and down for (int i = 0; i < matrix.length / 2; i++) { for (int j = 0; j < matrix[0].length; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[matrix.length - 1 - i][j]; matrix[matrix.length - 1 - i][j] = temp; } } //Swap position diagonal for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if(i == j)break; int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } }