1.题目
tag:easy array
https://leetcode-cn.com/problems/search-insert-position/
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
2.实现
分析:二分查找或者顺序查找
二分查找的时间复杂度为O(logn),顺序查找的O(n)。
Java
class Solution {
public int searchInsert(int[] nums, int target) {
int len = nums.length;
int i=0,j=len-1,mid=0;
if(nums[len-1]<target){
return len;
}
while(i<j){
mid=(i+j)/2;
if(target==nums[mid]){
return mid;
}else if(target<nums[mid]){
j=mid;
}else if(target>nums[mid]){
i=mid+1;
}
}
return i;
//return j;
//这里i=j
}
}
class Solution {
public int searchInsert(int[] nums, int target) {
int len = nums.length;
int i=0;
for(;i<len;i++){
if(nums[i]>=target){
break;
}
}
return i;
}
}
python
二分查找
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low=0
high=len(nums)
while low<high:
mid=(low+high)//2
if nums[mid]==target:
return mid
elif nums[mid]>target:
high=mid
#不能写成high=mid-1 防止mid=0时,high=-1
elif nums[mid]<target:
low=mid+1
return high
直接查找
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
n=len(nums)
i=0
if nums[n-1]<target:
return n;
for i in range(n):
if nums[i]>=target:
break
return i
3、注意
python3里面 a/b结果是浮点数,a//b结果才是向下取整