Search Insert Position


Description:

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.

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

Solution 1. Python

  • Time: O(lgn)
class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        low, high = 0, len(nums) - 1
        mid = int((low+high)/2)
        while(low < high):
            mid = int((low+high)/2)
            if nums[mid] < target:
                low = mid+1
            elif nums[mid] > target:
                high = mid
            elif nums[mid] == target:
                return mid

        if nums[low] >= target:
            return low
        elif nums[low] < target:
            return low + 1

Solution 2. Java

......

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

        if(nums[low] >= target) return low;
        else return low+1;
    }
}

results matching ""

    No results matching ""