Welcome to MarkdownPad 2
MarkdownPad is a full-featured Markdown editor for Windows.
leetcode 二分法通用解法
class Soultion
{
public:
int binarySearch(vector<int>&nums, int target)
{
if (nums.size() == 0)
{
return -1;
}
int start = 0;
int end = nums.size() - 1;
int mid;
while (start + 1 < end)/*避免相交或者相邻*/
{
mid = start + (end - start) / 2;
//start+end/2这种方法MAXINT可能会移除
if (nums[mid] == target) {
end = mid;
}
else if (nums[mid] < target)
{
start = mid;
}
else if (nums[mid] > target)
{
end = mid;
}
}
//判断取得是第一个还是第二个
if (nums[start] == mid)
{
return start;
}
if (nums[end] == mid)
{
return end;
}
return -1;
}
};