11. The search algorithm is simple and swift insertion position

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/huanglinxiao/article/details/91528373

Given a sorted array and a target, find the object in the array, and returns its index. If the target is not present in the array, it will be returned in sequence inserted position.

You may assume that no duplicate elements in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2
Example 2:

Input: [1,3,5,6], 2
Output: 1

solution:

 func searchInsert(_ nums: [Int], _ target: Int) -> Int {
        guard !nums.isEmpty else {
            return 0
        }
        var index = 0
        
        for item in 0..<nums.count {
            if target >= nums[item] {
                guard item < nums.count else{
                    break
                }
                if target == nums[item]{
                    index = item
                }else{
                    index = item + 1
                }
            }
        }
        return index
    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/91528373