35. Search Insert Position 查找插入位置

来源:互联网 发布:php登陆后显示用户名 编辑:程序博客网 时间:2024/05/08 08:22

Given a sorted array 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 may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5Output: 2

Example 2:

Input: [1,3,5,6], 2Output: 1

Example 3:

Input: [1,3,5,6], 7Output: 4

Example 1:

Input: [1,3,5,6], 0Output: 0

class Solution {    public int searchInsert(int[] nums, int target) {        int left=0;        int right=nums.length-1;        while(left<=right){            int mid=(right-left)/2+left;            if(nums[mid]<target){                left=mid+1;            }else if(nums[mid]>target){                right=mid-1;            }else{                return mid;            }        }        return left;    }}

解题思路:

相当于快排二分法,每次跟数组里面的middle位置的值进行比较,知道left等于right为止,也就是只剩下一个数值。

为了防止right和left是数值很大的值,(left+right)/2可能会造成overflow,所以采用(right-left)/2+left来表示mid位置。

关于最后return left是因为循环的部分是只要left<=right,只要没有比较出结果,就一直二分法进行下去,所以如果没有跟数组里面的某个值相等的话,最后return的left值就是应该插入的位置





阅读全文
0 0