LeetCode 33. Search in Rotated Sorted Array
题意:
Suppose a sorted array 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.
思路:
先找到分界点。找分界点参考:http://www.cnblogs.com/gufeiyang/p/5291679.html
找分界点,二分的时候边界一定要处理好。
找到边界后,选择一部分继续二分找到答案。
AC代码:
class Solution { public: int search(vector<int>& nums, int target) { int n = nums.size(); if(n == 0) return -1; int L = 0, R = n-1; if(nums[0] < nums[n-1]) { L = 0; R = n-1; } else { int left = 0, right = n-1; while(left<right) { int mid = (left+right)/2; if(nums[mid]>=nums[0]) left=mid+1; else if(nums[mid] < nums[0]) right = mid; } while(left>0 && nums[left]>nums[left-1]) left--; if(nums[n-1] >= target) { L = right; R = n-1; } else { L = 0; R = right-1; } } while(L <= R) { int mid = (L+R)/2; if(nums[mid] == target) return mid; else if(nums[mid] < target) L = mid+1; else R = mid-1; } return -1; } };

浙公网安备 33010602011771号