Tuesday, February 10, 2015

LeetCode [35] Search Insert Position

35. Search Insert Position
Easy

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], 5
Output: 2

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
//c++
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int n = nums.size();
        
        for(int i=0; i<n; ++i){
            if(nums[i]>=target) return i;
        }
        return n;
    }
};

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int n = nums.size(), l = 0, r = n-1;
        
        while(l<=r){
            int m = (l+r)/2;
            if(nums[m]==target) return m;
            if(nums[m]<target && (m==n-1||nums[m+1]>target)) return m+1;
            if(nums[m]<target) l = m+1;
            else r = m-1;
        }
        
        return 0;
    }
};

//Java
class Solution {
    public int searchInsert(int[] nums, int target) {
        int n = nums.length;
        int l = 0, r = n-1;
        
        //find m such that nums[m-1] < target <= nums[m]
        while(l<=r){
            int m = (l+r)/2;
            if(nums[m] < target){
                l = m+1;
            }else{//target<=nums[m]
                if(m==0) return m;
                else if(target<=nums[m-1]){
                    r = m-1;
                }else{//target>nums[m-1]
                    return m;
                }
            }
        }
        return n;
    }
}

No comments:

Post a Comment