给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5 输出: 2
示例 2:
输入: [1,3,5,6], 2 输出: 1
示例 3:
输入: [1,3,5,6], 7 输出: 4
示例 4:
输入: [1,3,5,6], 0 输出: 0
def search_insert(nums, target):
for i in range(len(nums)):
if nums[i] >= target:
return i
return len(nums)
if __name__ == '__main__':
nums = [1, 3, 5, 6]
target = 4
print(search_insert(nums, target))
def search_insert(nums, target):
if not nums or nums[0] > target:
return 0
if nums[len(nums) - 1] < target:
return len(nums)
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
# 找不到再判断与nums[mid]大小,返回索引
return mid if nums[mid] > target else mid + 1
if __name__ == '__main__':
nums = [1, 3, 5, 6]
target = 4
print(search_insert(nums, target))
思路1:遍历一遍原数组,若当前数字大于或等于目标值,则返回当前坐标,如果遍历结束了,说明目标值比数组中任何一个数都要大,则返回数组长度n即可;
class Solution {
public int searchInsert(int[] nums, int target) {
//遍历法
for(int i=0;i<nums.length;i++) {
if(nums[i]>=target) return i;
}
return nums.length;
}
}
思路2:我们还可以用二分搜索法来优化我们的时间复杂度。
public class Solution {
public int searchInsert(int[] nums, int target) {
//特殊情况
if(nums.length == 0 || nums[0] > target)
return 0;
if(nums[nums.length - 1] < target)
return nums.length;
//先二分查找,找到了就返回
int low = 0;
int hight = nums.length - 1;
int mid = 0;
while(low <= hight){
mid = (low + hight)/2;
if(nums[mid] < target){
low = mid + 1;
}else if(nums[mid] > target){
hight = mid - 1;
}else{
return mid;
}
}
//找不到再判断与nums[mid]大小,返回索引
return nums[mid] > target?mid:mid+1;
}
}
class Solution {
public int searchInsert(int[] nums, int target) {
//二分法
int left=0,right=nums.length-1;
//此处有=,则返回left;此处无=,返回right,且要判断数组最后一位与target的大小
while(left<=right) {
int mid=(left+right)/2;
if(nums[mid]==target) {
return mid;
}else if(nums[mid]>target) {
right=mid-1;
}else {
left=mid+1;
}
}
return left;
}
}
参考资料
[1] 搜索插入位置:Search Insert Position
[2] [LeetCode] Search Insert Position 搜索插入位置
[3] LeetCode-面试算法经典-Java实现】【035-Search Insert Position(搜索插入位置)】
[4] [Leetcode] 35. Search Insert Position 搜索插入位置