IncredibleThings

导航

LeetCode-Search Insert Position

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
public class Solution {
    public int searchInsert(int[] nums, int target) {
        if(nums==null || nums.length==0){
            return -1;
        }
        int res=-1;
        int len=nums.length;
        int low=0;
        int high=len-1;
        while(low<=high){
            int mid=low+(high-low)/2;
            if(mid==low){
                if(target>nums[mid]){
                    if(target<=nums[high]){
                        return mid+1;
                    }
                    else{
                        return high+1;
                    }
                }
                else{
                    return mid;
                }
            }
            else{
                if(nums[mid]==target){
                    return mid;
                }
                else if(nums[mid]<target){
                    low=mid+1;
                }
                else{
                    high=mid-1;
                }
            }
        }
        return 0;
    }
}

 二刷解法:

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

 

posted on 2016-08-06 01:17  IncredibleThings  阅读(140)  评论(0编辑  收藏  举报