Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, return the position where it will be inserted in order.

func searchInsert(_ nums: [Int], _ target: Sorted ().sorted().firstindex (of: target)! If let math = nums.firstIndex(of: target) { print(math) return math }else{ for (index,item) in nums.enumerated() { if item >= target { print(index) return Index}}} print(nums.count) return nums.count Var left = 0 var right = nums.count -1 while left <= right {let middle = left + (right-left)>>1 if nums[middle] < target { left = middle+1 }else if nums[middle] > target{ right = middle - 1 }else{ print(middle) return middle } } print(left) return left }Copy the code

Conclusion:

  • The first solution is amazing to me, but it’s still possible to play this way. What a god

  • The second is the for loop thinking that I first thought of

  • The third way is after you look at the problem area, you can use dichotomy to solve the problem

    • The dichotomy method only works in sorted arrays
    • Middle +1 when the left is greater than the middle
    • If the right-hand side is greater than the median, it’s middle-1
    • Returns middle if equal
    • When you break out of the loop, go back to the left