033 Search in Rotated Sorted Array[Leetcode]
2015-08-03 23:55
465 查看
题目描述
Suppose a sorted array is rotated at some pivot unknown to youbeforehand.
(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.
虽然是旋转过的,但本质上是有序的,并且分为最多两段(也可能旋转的位置就是头部,即没有元素被旋转)。如果线性查找就没有利用分段有序的特性,查找的时间为O(n)。既然是查找,不难想到使用二分法,时间复杂度可降到O(log n)。而这边的二分法需要加入对二分方向的判断。
以4567012为例,中间数字mid为7,mid > end,说明旋转后的最小值在7的右边。如果要找的target值大于4且小于7,那么在start和mid-1之间继续二分;如果要找的值比start小,那么在mid+1和end之间继续二分查找。
另一种情况是,旋转后的最小值位于mid的左边,如6701234。它的特征是mid < start。如果target值大于end,那么在start和mid-1之间继续二分;否则在mid+1和end之间继续二分。
class Solution { public: int search(vector<int>& nums, int target) { return helper(0, nums.size() - 1, nums, target); } //Basic Binary Search with considering two added situations because of rotation. int helper(int start, int end, const vector<int> &A, int target){ int mid=(start+end)/2; if(A[mid]==target) return mid; if(start>=end) return -1; if(target<A[mid]){ //consider the situation when part of the values that less than A[mid] was rotated to the right. if(A[mid]>A[end]&&target<A[start]) return helper(mid+1, end, A, target); else return helper(start, mid-1, A, target); } else{ //consider the situation when part of the values that larger than A[mid] was rotated to the left. if(A[mid]<A[start]&&target>A[end]) return helper(start, mid-1, A, target); else return helper(mid+1, end, A, target); } } };
相关文章推荐
- 08 JAVA 线程
- Joke with permutation
- jQuery - 自定义li元素的FocusColor
- poj 1681 高斯消元 枚举自由元求翻转最小次
- C#中的i++和++i
- hdoj1113(字符串map应用)
- leetcode 71: Simplify Path
- HDU - 3416 Marriage Match IV (最大流)
- spring 事务传播属性
- Java学习笔记(九) Bitset
- android_菜单的创建_xUtils框架使用
- android屏幕适配
- 连接SSO CAS的代码示例
- FFmpeg源代码结构图 - 编码
- POJ_1986_Distance Queries(LCA+tarjan)
- 升级win10,提示(RAM)内存不足2G的解决办法,亲测可行
- poj 1840
- JDK动态代理浅析
- hd2553 N皇后问题
- UVA 11925 Generating Permutations 生成排列 (序列)