6、Search in Rotated Sorted Array
2016-04-08 本文已影响30人
一念之见
Problem Description
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.
Analyze
二分查找法:
如果中间元素正好是要查找的元素,则搜素过程结束;
如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。
在A[mid] != target情况下:
若A[mid] < A[end],mid右边升序
若A[mid] > A[end],mid左边升序
时间复杂度: O(logn)
Code
class Solution {
func search(nums: [Int], _ target: Int) -> Int {
var start = 0, end = nums.count - 1
while (start <= end) {
let mid = start + (end - start) / 2
if nums[mid] == target { return mid }
if nums[mid] < nums[end] { // right half sorted
if target > nums[mid] && target <= nums[end] {
start = mid + 1
}
else { end = mid - 1}
}
else { // left half sorted
if target >= nums[start] && target < nums[mid] {
end = mid - 1
}
else { start = mid + 1 }
}
}
return -1
}
}
Search in Rotated Sorted Array II
Problem Description
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
Analyze
若A[mid] == A[end] (!= target),无法判定右边搜寻区间为[start , end-1]
Code
class Solution {
func search(nums: [Int], _ target: Int) -> Bool {
var start = 0, end = nums.count - 1
while (start <= end) {
let mid = start + (end - start) / 2
if nums[mid] == target { return true }
if nums[mid] < nums[end] {
if target > nums[mid] && target <= nums[end] {
start = mid + 1
}
else { end = mid - 1}
}
else if nums[mid] > nums[end] {
if target >= nums[start] && target < nums[mid] {
end = mid - 1
}
else { start = mid + 1 }
}
else { end -= 1 }
}
return false
}
}