[leedcode]–35. Search Insert Position

来源:互联网 发布:java摇奖机转盘 编辑:程序博客网 时间:2024/05/16 10:54

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.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

/*  错误的解法,应该摒弃这种错误的想法 for(int i =0;i<nums.length;i++){            if(i == nums.length-1){                return nums.length;            }else if(nums[0]>target){                return 0;            }            else if(nums[i]<target&&nums[i+1]>target){                return i+1;            }else if(nums[i]>target&&nums[i+1]>target){                return i-1;            }else if(nums[i] == target){                return i;            }        }        return 0;*/    //其实就是二分法插入数据即可解决        int low =0,high=nums.length-1;        int mid ;        while (low<=high){            mid=(low+high)/2;            if(nums[mid]  == target) return mid;            else if(nums[mid]<target) low = mid+1;            else high = mid-1;        }        return low;
原创粉丝点击