Searching in a rotated and sorted array
2014-07-09 09:31
225 查看
Given a sorted array that has been rotated serveral times. Write code to find an element in this array. You may assume that the array was originally sorted in increasing order.
思路:first to know that to ratate an array multiple times is no different than to rotate it just once.
No matter how the array has been rotated, it would fall into 3 kinds of situations below:
#1: If array[low] < array[mid], then left side is ordered normally.
#2: If array[mid] < array[high], then right side is ordered normally.
#3: array[mid] = array[low] = array[high], this might occur only when duplicates are allowed. In this condition, we have to search both sides because we don't know which side is ordered normally.
Note: a little tricky thing is that when array has exactly 2 elements, the above logic may go wrong, so just consider this situation separately.
思路:first to know that to ratate an array multiple times is no different than to rotate it just once.
No matter how the array has been rotated, it would fall into 3 kinds of situations below:
#1: If array[low] < array[mid], then left side is ordered normally.
#2: If array[mid] < array[high], then right side is ordered normally.
#3: array[mid] = array[low] = array[high], this might occur only when duplicates are allowed. In this condition, we have to search both sides because we don't know which side is ordered normally.
Note: a little tricky thing is that when array has exactly 2 elements, the above logic may go wrong, so just consider this situation separately.
相关文章推荐
- Searching an Element in a Rotated Sorted Array
- 81. Search in Rotated Sorted Array II (Array; Divide-and-Conquer)
- 153. Find Minimum in Rotated Sorted Array (Array; Divide-and-Conquer)
- 【LeetCode】Find Minimum In Rotated Sorted Array 1 and 2
- Find the Minimum Element in A sorted and Rotated Array
- Leetcode: Searching an Element in a Rotated Sorted Array I
- Leetcode_search-in-rotated-sorted-array-ii(updated c++ and python version)
- [LeetCode] Search in Rotated Sorted Array
- leetcode 97: Search in Rotated Sorted Array
- [LeetCode] Search in Rotated Sorted Array II
- Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array 解题报告
- [Leetcode] Search in Rotated Sorted Array
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array
- LeetCode: Search in Rotated Sorted Array II
- [leetcode] Search in Rotated Sorted Array
- [Leetcode] Search in Rotated Sorted Array II
- leetcode 98: Search in Rotated Sorted Array II
- LeetCode: Search in Rotated Sorted Array
- Search in Rotated Sorted Array