链接:
https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
题目:
假设按照升序排序的数组在预先未知的某个点上进行了旋转。( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:
输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
我的解法:(28ms,击败92%)先判断当前mid的位置,分别做判断。
比方[5671234],tar=2。 mid = 1,此时,如果target在1-4之间,取右半边;target小于1或者大于4在左边。写得挺繁琐的。。
class Solution:
def search(self, nums, target):
if nums == []:
return -1
left = 0
right = len(nums) - 1
while left <= right:
mid = int((left + right)/2)
if target == nums[mid]:
return mid
if nums[left] > nums[mid]:
if target > nums[mid] and target <= nums[right]:
left = mid + 1
elif target < nums[mid] or target > nums[right]:
right = mid - 1
elif nums[left] < nums[mid]:
if target >= nums[left] and target < nums[mid]:
right = mid - 1
elif target > nums[mid] or target < nums[left]:
left = mid + 1
else:
if nums[right] == target:
return right
else:
return -1
别人的解法:思路类似,精简版,优秀
class Solution:
def search(self, nums, target):
if not nums:
return -1
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) / 2
if target == nums[mid]:
return mid
# 左边的序列是正序排列的
if nums[low] <= nums[mid]:
# target在前半部分正排序内
if nums[low] <= target <= nums[mid]:
high = mid - 1
else:
low = mid + 1
# 左边是先增后小的,说明后半部分是正序排列
else:
# 如果target在后半部分排列内
if nums[mid] <= target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return -1
别人的解法2: 计算mid的时候,不同情况下赋值成inf,或者-inf;就可以直接做二分查找了。
Let’s say nums looks like this: [12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], Because it’s not fully sorted, we can’t do normal binary search. But here comes the trick:
If target is let’s say 14, then we adjust nums to this, where “inf” means infinity:
[12, 13, 14, 15, 16, 17, 18, 19, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf]
If target is let’s say 7, then we adjust nums to this:
[-inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
And then we can simply do ordinary binary search.
int search(vector<int>& nums, int target) {
int lo = 0, hi = nums.size();
while (lo < hi) {
int mid = (lo + hi) / 2;
double num = (nums[mid] < nums[0]) == (target < nums[0])
? nums[mid]
: target < nums[0] ? -INFINITY : INFINITY;
if (num < target)
lo = mid + 1;
else if (num > target)
hi = mid;
else
return mid;
}
return -1;
}
python版本:新思路
class Solution:
def search(self, nums, target):
if not nums:
return -1
low, high = 0, len(nums) - 1
while low <= high:
mid = int((low + high) / 2)
#num_mid = nums[mid]
if target < nums[low] and nums[mid] >= nums[low]:
nums[mid] = - float("inf")
elif target >= nums[low] and nums[mid] < nums[low]:
nums[mid] = float("inf")
if target < nums[mid]:
high = mid - 1
elif target > nums[mid]:
low = mid + 1
else:
return mid
return -1