LeetCode: Search in Rotated Sorted Array
2015-04-21 14:24
344 查看
Title:
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
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.
思路:还是二分搜索,但是对于一个中间值,如何处理是左加还是右加呢?考虑下,旋转之后的数组,中间值会将原来的数组划分为左右两个数组,其中一个是有序的。所以我们需要做的事就是判断那边是有序的。如何判断有序呢?只要将中间值和最左边的值比较,如果大于,则左边是有序,如果小于,则右边有序,如果相等,则有重复元素只能一个个处理。
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
0 1 2 4 5 6 7might 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.
思路:还是二分搜索,但是对于一个中间值,如何处理是左加还是右加呢?考虑下,旋转之后的数组,中间值会将原来的数组划分为左右两个数组,其中一个是有序的。所以我们需要做的事就是判断那边是有序的。如何判断有序呢?只要将中间值和最左边的值比较,如果大于,则左边是有序,如果小于,则右边有序,如果相等,则有重复元素只能一个个处理。
class Solution { public: int search(int A[], int n, int target) { int l = 0; int h = n-1; while (l <= h){ int m = (l+h)/2; if (A[m] == target) return m; if (A[m] > A[l]){ if (target >= A[l] && target < A[m]) h = m-1; else l = m+1; } else if (A[m] < A[l]){ if (target <= A[h] && target > A[m]) l = m+1; else h = m-1; } else l++; } return -1; } };
相关文章推荐
- leetcode 33. Search in Rotated Sorted Array
- LeetCode-81-Search in Rotated Sorted Array II 水题
- leetcode-Search in Rotated Sorted Array -java
- leetCode 33.Search in Rotated Sorted Array(排序旋转数组的查找) 解题思路和方法
- leetcode之Search in Rotated Sorted Array,剑指offer之旋转数组的最小数字
- [Leetcode] Search in Rotated Sorted Array II
- 20_leetcode_Search in Rotated Sorted Array
- LeetCode (33)Search in Rotated Sorted Array
- 33.search in rotated sorted array leetcode java
- leetcode_middle_85_33. Search in Rotated Sorted Array
- 【LeetCode题意分析&解答】33. Search in Rotated Sorted Array
- LeetCode - Search in Rotated Sorted Array
- LeetCode | Search in Rotated Sorted Array II
- Leetcode 33. Search in Rotated Sorted Array
- [leetcode ]Search in Rotated Sorted Array
- [LeetCode] Search in Rotated Sorted Array、Search for a Range、Search Insert Position、Search in Rotate
- LeetCode 33. Search in Rotated Sorted Array
- [LeetCode] Search in Rotated Sorted Array
- leetcode || 81、Search in Rotated Sorted Array II
- Search in Rotated Sorted Array II leetcode java