问题:33. Search in Rotated Sorted Array
题目描述:https://leetcode.com/problems/search-in-rotated-sorted-array/description/
大致意思是说,有一个升序无重复的数组,选择某一个位置对该数组进行前后两部分的交换,例如[0,1,2,4,5,6,7],交换后变成了[4,5,6,7,0,1,2],而这个位置是未知的。要求找到新数组中某一个元素的下标,若不存在则返回-1。
当然可以用O(n)去遍历找下标:
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length=len(nums)
if length==0:
return -1
res=-1
for i in range(length):
if nums[i]==target:
res=i
break
return res
下面给出一个改进的二分查找,时间复杂度O(nlogn),思想如下:
由于数组中没有重复元素,对于某一个下标index:
1、如果满足nums[0]<nums[index],那么数组nums[0...index]是有序且升序的;
2、如果有nums[0]>nums[index],那么nums[0...index]之间必然存在下降点,也就是原数组中的反转点。更进一步,nums[index+1...end]的范围一定在nums[index]和nums[0]之间。
因此:
当nums[0]<=target<=nums[index]时,只需在nums[0...index]之间查找即可;
当target<=nums[index]<nums[0]时,由上面case2可知,target必然不存在于nums[index+1...end],故只需在nums[0...index]之间查找即可;
当nums[index]<nums[0]<=target时,同样只需在nums[0...index]之间查找即可,理由同上。
于是有如下代码:
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l,r=0,len(nums)-1
while l<=r:
mid=(l+r)//2
if nums[mid]==target:
return mid
if nums[l]<=target and target<=nums[mid]:
r=mid-1
elif nums[l]>nums[mid] and nums[mid]>=target:
r=mid-1
elif target>=nums[l] and nums[l]>nums[mid]:
r=mid-1
else:
l=mid+1
return -1
结束了吗?还没。其实我们可以写得更简洁一些:
观察上面三种情况,我们发现实际上只有三个判断条件:nums[0]<=target、target<=nums[index]和nums[index]<nums[0]。如果列出真值表会发现,三个条件同真或者同假的情况不存在,当有两个条件为真时,有r=mid-1;当有一个条件为真时,有l=mid+1。于是利用位运算的加法并取最低位可以简化成这样:
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r) // 2
if nums[mid] == target:
return mid
# if nums[l]<=target and target<=nums[mid]:
# r=mid-1
# elif nums[l]>nums[mid] and nums[mid]>=target:
# r=mid-1
# elif target>=nums[l] and nums[l]>nums[mid]:
# r=mid-1
if ((nums[l] <= target) + (target <= nums[mid]) + (nums[mid] < nums[l])) & 1:
l = mid + 1
else:
r = mid - 1
return -1
结束了吗?还没。又考虑到其实上面三个判断条件从左向右是循环的,因此还可以用位运算XOR(异或)实现,于是又能够写成这样:
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r) // 2
if nums[mid] == target:
return mid
# if nums[l]<=target and target<=nums[mid]:
# r=mid-1
# elif nums[l]>nums[mid] and nums[mid]>=target:
# r=mid-1
# elif target>=nums[l] and nums[l]>nums[mid]:
# r=mid-1
if ((nums[l] <= target) ^ (target <= nums[mid]) ^ (nums[mid] < nums[l])):
l = mid + 1
else:
r = mid - 1
return -1
结束了吗?嗯。