问题:
难度:easy
说明:
给出一个数字Target,查找它在已经排序的数组arr里面的插入位置,如果发现数组有了元素就返回该坐标,如果没有就返回需要插入的坐标,我们可以用遍历或者二分法处理。
问题链接:https://leetcode.com/problems/search-insert-position/
输入案例:
// 5已经存在,而且坐标索引为2
Example 1:
Input: [1,3,5,6], 5
Output: 2
// 2不存在,但是插入坐标索引为1的数组内
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
我的代码:
水题,先贴一个遍历的,然后贴一个二分法当做练习。
class Solution {
public int searchInsert(int[] nums, int target) {
// 定义索引i
int i = 0;
// 如果发现数组元素小于等于就跳出,因为该索引刚好是目标索引
for(;i < nums.length;i ++) if(target <= nums[i]) break;
return i;
}
}
二分法:
二分法leetcode有说具有三个模板,我使用了其中一个left, mid, right index assignments,三索引可分配(就大概这样子)。
因为这个模板可以
No post-processing required because at each step, you are checking to see if the element has been found. If you reach the end, then you know the element is not found
就是不会后置处理,你可以准确预测元素类型何种情况,比如你遍历中找到则是命中,如果你跳出了查找,意味着找不到,而且绝对准确滴命中元素。(反正我信了)
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int mid = 0;
// 要求最终是夹住元素坐标,而且是left为准
while(right >= left) {
mid = left + right >> 1;
// 这里如果是找到就返回mid
if(nums[mid] == target) return mid;
if(nums[mid] > target) right = mid - 1;
if(nums[mid] < target) left = mid + 1;
}
// 因为left从0开始,如果元素0插入,left可以做到,如果数组末插入,left + 1也可以做到
return left;
}
}