题目链接
class Solution {public int searchInsert(int[] nums, int target) {int len = nums.length;int left = 0;int right = len - 1;int index = -1;while(left <= len / 2){if(nums[left] == target || target < nums[left]){index = left;break;}else{left++;}if(nums[right] == target){index = right;break;}else if(target > nums[right]){index = right + 1;break;}else{right--;}}return index;}
}
采用二分查找可以顺利找到target
存在于数组中的位置;
当target
不存在与数组中时需要对左右两侧分别考虑,由于数组下标从0开始且为有序数组,所以当target < nums[left]
则index = left
,当target > nums[right]
则index = right + 1
官方题解
class Solution {public int searchInsert(int[] nums, int target) {int n = nums.length;int left = 0, right = n - 1, ans = n;while (left <= right) {// 相当于int mid = (left + right) / 2int mid = ((right - left) >> 1) + left;if (target <= nums[mid]) {ans = mid;right = mid - 1;} else {left = mid + 1;}}return ans;}
}
思路:即不断用二分法逼近查找第一个大于等于target
的下标 。下文给出的代码是笔者习惯的二分写法,ans
初值设置为数组长度可以省略边界条件的判断,因为存在一种情况是target
大于数组中的所有数,此时需要插入到数组长度的位置。
(答案的写法确实简洁欸!!!!我觉得我的思路和答案是一样的呜!!!!)