Search Insert Position – LeetCode 35
Problem
Description
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.
Example
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
Answer
Original
Code
1 | class Solution { |
思路
最简单的线性遍历,就是展示下。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$6$ ms,排名$66.33\%$
Better
思路
基础的二分查找,时间复杂度$O(\log_{2}{n})$,空间复杂度$O(1)$。
耗时$6$ ms,排名$66.33\%$
Code
1 | class Solution { |