[LeetCode] Search in Rotated Sorted Array
2015-07-23 22:32 codinglol 阅读(123) 评论(0) 编辑 收藏 举报题目要求:
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.
解题思路:
这是一个查找的问题,首先,从头到尾遍历一遍肯定可以解决,但花费的时间为O(n),这里就需要思考其他的解法。
对于这个部分有序的数组可以试着采用二分查找,需要解决的问题是如何去缩小查找目标所在的范围。
反转的有序数组可能出现以下三种情况:
我们可以据此分情况讨论,具体参见代码
int search(int* nums, int numsSize, int target) { int first = 0, end = numsSize - 1; while(first <= end){ int mid = first + (end - first) / 2; if(nums[mid] == target) return mid; if(nums[first] <= nums[mid]){ if(nums[first] <= target && nums[mid] > target) end = mid - 1; else first = mid + 1; } else{ if(nums[mid] < target && nums[end] >= target) first = mid + 1; else end = mid - 1; } } return -1; }