1, Title Requirements
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, returns where it will be inserted sequentially.
You can assume that there are no duplicate elements in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
2. Disintegration ideas
Brute force - loop traversal, determine the size of data, time
//brute-force attack static int searchInsert(int[] nums, int target){ for (int i=0;i<nums.length;i++){ int vi = nums[i]; if (i<nums.length-1){ int n = i+1; int vi1 = nums[n]; if (vi > target){ System.out.println(0); return 0; } if (vi == target){ System.out.println(i); return i; } if (vi<target && target<vi1){ System.out.println(n); return n; } }else { if (vi<target) { System.out.println(nums.length); return nums.length; }else { System.out.println(nums.length-1); return nums.length-1; } } } return 0; }
This method is to see the official solution and realize it by yourself
//Two points search static int searchInsert2(int[] nums, int target){ int left = 0, right = nums.length - 1; int rs = 0; while(left <= right) { int mid = (left + right) / 2; if(nums[mid] == target) { // Related logic return mid; } else if(nums[mid] < target) { left = mid + 1; rs = left; } else { right = mid - 1; if (right < 0){ return 0; } rs = mid; } } // Related return value return rs; }
If the epidemic situation has no lover, analyze and brush the questions;