建议先看这里:二分查找。
Problem
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
Solution
one
WTF 折腾了大半早上
本来是直接定义low/high为decltype(nums.size()),但是,当出现-1时候,出问题啊,decltype(nums.size())是unsigned long int…
这下对二分查找算是整的清楚了,以后边界定义就按照这个来,二分查找,就不用!=
了。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ret(2, -1);
int n = nums.size();
int low = 0, high = n-1, mid;
while (low <= high) {
mid = low + (high - low) / 2;
if (nums[mid] == target) {
low = mid; //找到后,往前/后继续查找范围
high = mid;
while (low != -1 && nums[low] == target) {
--low;
}
ret[0] = low+1;
while (high != n && nums[high] == target) {
++high;
}
ret[1] = high-1;
return ret;
}
else if (nums[mid] < target) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return ret;
}
};
runtime: 9ms
时间貌似挺快的
two
date: 2016.9.16
思路请看关于二分
class Solution {
public:
int upper_bound(vector<int> &nums, int low, int high, int target) {
int mid;
while (low < high) {
mid = low + (high-low)/2;
if (nums[mid] <= target) {
low = mid+1;
}
else {
high = mid;
}
}
return low;
}
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> v(2, -1);
int n = (int)nums.size();
if (n == 1 && nums[0] != target) {
return v;
}
if (n == 1 && nums[0] == target) {
v[0] = 0;
v[1] = 0;
return v;
}
if (nums[n-1] < target) {
return v;
}
if (nums[0] > target) {
return v;
}
int low = 0, high = n;
high = upper_bound(nums, low, high, target);
if (nums[--high] != target) {
return v;
}
v[1] = high;
while (high >= 0 && nums[high] == target) {
--high;
}
if (high >= 0) {
v[0] = ++high;
return v;
}
v[0] = 0;
return v;
}
};
runtime: 9ms
关于二分
date: 2016.9.16
二分查找,花了不少时间,重新写一份关于二分查找的吧,算是给二分一个结局,地址:二分查找。