LeetCode #35 Search Insert Position

LeetCode #35 Search Insert Position

Question

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

Solution

Approach #1

class Solution {
    func searchInsert(_ nums: [Int], _ target: Int) -> Int {
        for i in 0..<nums.count {
            if target <= nums[i] {
                return i
            }
        }
        return nums.count
    }
}

Time complexity: O(n).

Space complexity: O(1).

Approach #2

class Solution {
    func searchInsert(_ nums: [Int], _ target: Int) -> Int {
        var l = 0
        var h = nums.count - 1
        var m = 0
        while l <= h {
            m = l + (h - l) / 2
            if target > nums[m]  {
                l = m + 1
            } else if target < nums[m] {
                h = m - 1
            } else {
                return m
            }
        }
        return l
    }
}

Time complexity: O(log(n)).

Space complexity: O(1).

转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/7067407.html

原文地址:https://www.cnblogs.com/silence-cnblogs/p/7067407.html