day2力扣leetcode(二分查找)—#35.搜索插入位置
1.题目描述:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n)
的算法。
示例 1:
输入: nums = [1,3,5,6], target = 5
输出: 2
示例 2:
输入: nums = [1,3,5,6], target = 2
输出: 1
示例 3:
输入: nums = [1,3,5,6], target = 7
输出: 4
提示:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
为 无重复元素 的 升序 排列数组-104 <= target <= 104
2.题解
2.1暴力解(c++)
暴力解题 不一定时间消耗就非常高,关键看实现的方式,就像是二分查找时间消耗不一定就很低,是一样的。代码如下:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int i;
int j = nums.size();
for(i=0;i<j;i++){
if(nums[i]>=target)
return i;
}
return j;
}
};
2.2二分查找(c++)
注意这道题目的前提是数组是有序数组,这也是使用二分查找的基础条件。
以后只要看到面试题里给出的数组是有序数组,都可以想一想是否可以使用二分法。
同时题目还强调数组中无重复元素,因为一旦有重复元素,使用二分查找法返回的元素下标可能不是唯一的。
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n=nums.size();
int left=0;
int right=n-1;
while(left<=right){
int middle = left+(right-left)/2;
if(nums[middle]==target)
return middle;
else if (nums[middle]>target)
right = middle - 1;
else
left = middle + 1;
}
return right +1;
}
};
2.3 python
内置函数1
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target in nums:
return nums.index(target)
else:
nums.append(target) '''append函数是向列表末尾添加函数'''
nums.sort()
return nums.index(target)
但是此方法没有符合题意,sort()时间复杂度为nlogn,这里写出来只是提供一种思路。
内置函数2
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
return bisect.bisect_left(nums,target)
python内部提供了二分查找的函数,bisect模块中有bisect_left和bisec_right函数,具体使用在以后的文章中介绍,有想了解的可以自行去查官方文档。
二分查找
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
middle = (left + right) // 2
if nums[middle] < target:
left = middle + 1
elif nums[middle] > target:
right = middle - 1
else:
return middle
return right + 1
以后会出几期关于python内置函数的介绍,敬请期待哟~