Search Insert Position
Total Accepted: 4060 Total Submissions: 12013My Submissions
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.
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 → 0
Recommedation, STL implement, use first and length to binary search:
class Solution:
def searchInsert(self, nums, target):
#search lower bound 刚好是第一个插入的位置!!!
first,cur_len = 0,len(nums)
while (cur_len > 0):
half = cur_len >> 1
if (nums[first+half] < target):
first = first+half+1
cur_len = cur_len-(half+1)
else: #这个因为是nums[first+half] 肯定>= target,所以只保留nums[0..first+half-1],如果上一个if里的元素都比target小,只能插在末尾
cur_len = half
return first
def searchUpperBound(self, nums, target):
# search upper bound 刚好是最后一个插入的位置!!!
first,cur_len = 0,len(nums)
while (cur_len > 0):
half = cur_len >> 1
if (nums[first+half] <= target):
first = first+half+1
cur_len = cur_len-(half+1)
else: #这个因为是nums[first+half] 肯定> target,所以只保留nums[0..first+half-1],如果上一个if里的元素都小于等于target,只能插在末尾
cur_len = half
return first
s = Solution()
y = s.searchInsert([1,3,5,6],2)
print(y)
If dropping the left part will break the loop, mid + 1 is the answer;
If dropping the right part will break the loop, mid is the answer;
The AC code is ,but it's bad code format
class Solution {
public:
int searchInsert(int A[], int n, int target) {
int l = 0, r = n - 1, mid;
while (l <= r) {
mid = (l + r) / 2;
if (A[mid] == target)
return mid;
else if (A[mid] > target) {
if (mid - 1 >= l)
r = mid - 1;
else
return mid;
}
else if (A[mid] < target) {
if (mid + 1 <= r)
l = mid + 1;
else
return mid + 1;
}
}
return mid;
}
};

本文介绍了一个高效的算法,用于在一个已排序的数组中找到目标值的插入位置。通过使用二分查找的方法,该算法能够在O(log n)的时间复杂度内完成搜索任务。文中还提供了具体的Python实现代码,并附带了几个示例说明如何使用该算法。
496

被折叠的 条评论
为什么被折叠?



