您的位置:首页 > 其它

leetcode第十四周解题总结--二分查找

2017-06-25 18:13 453 查看

35. Search Insert Position

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

题意解析:

给出一个数组和一个目标值,如果找到目标值则返回下标,否则返回按序插入的下标。

解题思路:

首先直接想到遍历数组,找到等于或者大于目标值的下标即可。

class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
if(nums[i] >= target) return i;
}
return nums.size();
}
};


但是排序后的数组都可以使用二分查找来减小时间复杂度。

class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int l = 0;
int r = nums.size() - 1;
while(l<r) {
int m = (l + r)/2;

if(nums[m] == target) return m;
if(nums[m] > target) {
r = m-1;
}else{
l = m+1;
}
}
return nums[l]>=target?l:(l+1);
}
};


注意最后的取值,如果最后的值大于等于目标值,则取最后得到的下标,而如果最后的值小于目标值,则取(下标+1)。

153. Find Minimum in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array.

题意解析:

找到一个旋转数组中的最小值。

解题思路:

直接的想到遍历数组寻找到旋转点,如果存在旋转点那么就是最小值。

class Solution {
public:
int findMin(vector<int>& nums) {
int p = 0;
for(int i = 0; i < nums.size() - 1;i++) {
if(nums[i] > nums[i+1]){
p = i + 1;
break;
}
}
return nums[p];
}
};


同样还是可以用二分查找的方法,如果左边大于右边,则说明还没到达旋转点,相反,则说明在同一段有序数组内。

class Solution {
public:
int findMin(vector<int>& nums) {
int l = 0;
int r = nums.size() -1;
while(l < r && nums[l] >nums[r]) {
int m = (l + r) /2;
if(nums[m] > nums[r]) {
l = m + 1;
}else {
r = m;
}
}
return nums[l];
}
};


154. Find Minimum in Rotated Sorted Array II

Follow up for “Find Minimum in Rotated Sorted Array”:

What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

The array may contain duplicates.

题意解析:

找到一个旋转数组中的最小值,允许存在重复的数字。

解题思路:

上题的第一种解法可以直接A,不受影响。

而使用二分查找的时候需要多加一定的判断:

如果左边大于等于右边,则还没到达旋转点,如果中间点大于左边,说明还在左边半段,如果中间点小于左边,说明已经在右边半段。如果中间点等于左边,不好判断中间点的位置,则使得左边点右移一位,跳过这个重复值再进行判断。

class Solution {
public:
int findMin(vector<int>& nums) {
int l = 0;
int r = nums.size() -1;
while(l < r && nums[l] >=nums[r]) {
int m = (l + r) /2;
if(nums[m] > nums[l]) {
l = m + 1;
}else if(nums[m] < nums[l]){
r = m;
}else{
l = l+1;
}
}
return nums[l];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: