35. Search Insert Position&& 278. First Bad Version

来源:互联网 发布:白牌照是什么意思js 编辑:程序博客网 时间:2024/06/04 19:18

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



1.找到前面比目标小后面比目标大的位置
2.如果目标比最后一个元素大
class Solution {  public int searchInsert(int[] nums, int target) {        int res = 0;                if(nums==null||nums.length==0)            return 0;        for(int  i =0;i<nums.length;i++){            if(target==nums[i]){                res =  i;                break;            }            if(target>nums[i]){            if((i+1)==nums.length||target<nums[i+1]){                        res = i+1;            break;            }            }            else                continue;        }        return res;    }}

但是这种方法时间复杂度是O(n), 参考别人的做法 用二分搜索
class Solution {public int searchInsert(int[] nums, int target) {    int left = 0;    int right = nums.length-1;    while(left<=right){        int mid = (left+right)/2;        if(nums[mid]==target)            return mid;        else if(nums[mid]<target)            left = mid+1;        else            right = mid-1;    }    return left;}}

278.
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whetherversion is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

public class Solution extends VersionControl {    public int firstBadVersion(int n) {        int left=1,right=n;        while(left<right){            int mid = (right+left)/2;//这里这样写会报错Time Limit Exceeded 因为会超过integer的MAX_VALUE上限            if(!isBadVersion(mid))  left = mid+1;            else       right = mid;        }        return left;    }}

注意这一句应该写:int mid = (right+left)/2;

原创粉丝点击