Before entering the binary search module, we look at the binary thinking lookup.
topic
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
Example 3:
Input: [ 1 , 3 , 5 , 6 ], 7 Output: 4
Example 4:
Input: [ 1 , 3 , 5 , 6 ], 0 Output: 0
thought
If the subject of violence resolved, if desired,
(n-) O O ( n- ) time complexity, but if the two points, then it can be reduced to O (logN) O ( L O G n- ) time complexity
- Common whole idea and almost no difference binary search, is set to the left subscripts
left
and subscript rightright
, then calculates an intermediate indexmid
-
Determined each time according to the size between nums [mid] and the target, equal to the direct return subscript, nums [mid] <target is left to the right, nums [mid]> target the right left
- The search ends if no value is returned is equal to left, that is the insertion position
- Time complexity: O (logN)
Code
func searchInsert(_ nums: [Int], _ target: Int) -> Int { if nums[nums.count - 1] < target { return nums.count - 1 } var left = 0 var right = nums.count - 1 while left <= right { let middle = (left + right) / 2 if nums[middle] == target { return middle } else if nums[middle] < target { left = middle + 1 } else { right = middle - 1 } } return left }
result