[Leetcode] Search in Rotated Sorted Array
2014-10-18 04:59
344 查看
题目:
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.
思路:二分法,不过需要加一层判断条件。首先判断哪边是连续的,然后向左走还是向右走通过连续的那一部分去判断。
总结:复杂度为O(log n).
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 lower_bound = 0; int upper_bound = n - 1; while (lower_bound <= upper_bound) { int mid = (lower_bound + upper_bound) / 2; if (A[mid] == target) { return mid; } else if (A[mid] >= A[lower_bound]) { //left part consistent if (A[lower_bound] <= target && A[mid] > target) { //go left upper_bound = mid - 1; } else { //go right lower_bound = mid + 1; } } else { //right part consistent if (A[upper_bound] >= target && A[mid] < target) { //go right lower_bound = mid + 1; } else { //go left upper_bound = mid - 1; } } } return -1; } };
总结:复杂度为O(log n).
相关文章推荐
- [LeetCode] Search in Rotated Sorted Array II
- LeetCode : Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array 解题报告
- [leetcode] Search in Rotated Sorted Array
- [LeetCode]Search in Rotated Sorted Array
- leetcode 97: Search in Rotated Sorted Array
- LeetCode Search in Rotated Sorted Array
- [LeetCode] Search in Rotated Sorted Array II 解题报告
- [LeetCode] Search in Rotated Sorted Array
- [LeetCode] Search in Rotated Sorted Array
- [Leetcode] Search in Rotated Sorted Array
- leetcode 97: Search in Rotated Sorted Array
- LeetCode: Search in Rotated Sorted Array
- [leetcode] Search in Rotated Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array
- LeetCode : Search in Rotated Sorted Array
- leetcode 98: Search in Rotated Sorted Array II
- LeetCode_Search in Rotated Sorted Array
- [LeetCode] Search in Rotated Sorted Array II
- LeetCode —— Search in Rotated Sorted Array