python:
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
t = 0
for index, i in enumerate(nums):
if i >= target:
return index
return len(nums)c++:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while ( left <= right){
int mid = (left + right)/2;
if (target > nums[mid])
left = mid + 1;
else
right = mid - 1;
}
return left;
}
};

本文介绍了二分查找算法的两种实现方式:一种是使用Python语言,另一种是使用C++语言。这两种实现方式均能有效地找到目标值在有序数组中的插入位置。Python版本采用遍历方法,而C++版本则通过迭代实现了经典的二分查找。
206

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



