LeetCode算法题目: Search in Rotated Sorted Array

来源:互联网 发布:spss19软件安装 编辑:程序博客网 时间:2024/05/25 23:27

题目:

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).
You are given a target value to search. If found in the array return its index, otherwise
return -1.
You may assume no duplicate exists in the array.


分析:

此题目难度为hard,解此题目采用二分查找.难度在于如何确定边界。

二分查找算法就是不断将数组进行对半分割,每次拿中间元素和目标值进行比较。时间复杂度为O(log(n))


代码实现:

class Solution {public:    int search(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[mid] < target && target <= nums[last-1])              first = mid + 1;           else              last = mid;       }  }    return -1; }};
0 0