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.html

You may assume no duplicates in the array.swift

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 → 0app

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).code

Space complexity: O(1).htm

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)).blog

Space complexity: O(1).leetcode

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

相关文章
相关标签/搜索