Suppose an array sorted in ascending order 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.
题目大意:
假设按照升序排列的数组在事先未知的某个关键点上旋转。(即,0 1 2 4 5 6 7可能变成4 5 6 7 0 1 2)。给你一个目标值来搜索。 如果在数组中发现它返回其索引,否则返回-1。
你可能会认为数组中没有重复。
算法分析:
给定数据可能被关键点分为俩部分连续的子数组,我们根据二分法找到中位数,判断目标数落在哪儿个子组数组内,然后在子数组内用二分法找到目标数所在数据的位置,如未找到,则返回-1.
代码如下:
- Java
public int search(int[] nums, int target) {
if (nums.length <= 0)
return -1;
int start = 0;
int end = nums.length-1;
while (start+1 < end) {
int mid = start + (end-start)/2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > nums[start]) {
if (target >= nums[start] && target<=nums[mid])
end = mid;
else
start = mid;
} else {
if (target >= nums[mid] && target <= nums[end])
start = mid;
else
end = mid;
}
}
if (nums[start] == target)
return start;
if (nums[end] == target)
return end;
return -1;
}
- Python
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
start, end = 0, len(nums)-1
while start+1 < end:
mid = start +(int) ((end - start) / 2)
if nums[mid] == target:
return mid
elif nums[mid] > nums[start]:
if target>=nums[mid] and target<=nums[end]:
start == mid
else:
end == mid
else:
if target>=nums[start] && target<=nums[mid]:
end == mid
else:
start == mid
if nums[start] == target:
return start
if nums[end] == target:
return end
return -1
注: Python代码未在LeetCode验证通过,原因时间超出限制,有待优化。