您的位置:首页 > 编程语言

GEEK编程练习— —旋转排序数组中的查找

2016-04-19 15:34 239 查看

题目

假设一个已经排好序的数组,在某一个点进行了旋转,这个点不可知(如0,1,2,4,5,6,7旋转后变为4,5,6,7,0,1,2)。

输入整数n,如果n在数组里,返回n在数组中的索引,否则返回-1

分析

一般使用二分查找,要注意左右边界的确定。还要考虑到重复元素的存在。

代码

//Date:2016-04-18
//Author:Sin_Geek
//时间负责度O(n),空间复杂度O(1)

#include <vector>
#include <iostream>

using namespace std;

int search(const vector<int>& nums, int target)
{
int first = 0, last = nums.size();
while (first != last)
{
const int mid = first + (last - first) / 2;
if (nums[mid] == target)
return mid;
if (nums[first] < nums[mid])
{
if (nums[first] <= target && target < nums[mid])
last = mid;
else
first = mid + 1;
}
else if (nums[first] > nums[mid])
{
if (nums[mid] < target && target <= nums[last-1])
first = mid + 1;
else
last = mid;
}
else
first++;
}
return -1;
}
int main()
{
vector<int> nums = {1,2,3,1,1,1};
int target = 3;
cout << search(nums, target) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编程 二分查找 c++