【题目】
非负的有序数组中,如果有与target相同的,输出该数位置,如果没有,输出应该将target插到哪个位置
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n)
runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5 Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2 Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7 Output: 4
Example 4:
Input: nums = [1,3,5,6], target = 0 Output: 0
Example 5:
Input: nums = [1], target = 0 Output: 0
【思路】
- 细节方面可参考: https://www.cnblogs.com/kyoner/p/11080078.html
- 关联题开根号:https://www.cnblogs.com/inku/p/15157123.html
- 最好将所有题都写成最保险的情况,左闭右开
- 数字插入,需要找右区间
【代码】
class Solution { public int searchInsert(int[] nums, int target) { int left=0;int right=nums.length; while(left<right){ int mid=left+(right-left)/2; if(nums[mid]==target) return mid; else if(nums[mid]<target) left=mid+1; else if(nums[mid]>target) right=mid; } if(left==nums.length) return nums.length; return right;//总之不管怎样,要么右指针为target,要么右指针前面插入数字 } }
为什么left=mid+1,而right=mid?
左闭右开区间,nums.length也是取不到的,所以无需-1
if(left==nums.length) return nums.length
左区间都到最右边了还没找到target,数组又是有序的,那target比所有数都大,插到最后