#154 Find Minimum in Rotated Sorted Array II (Hard)
Suppose an array of length
nsorted in ascending order is rotated between1andntimes. For example, the arraynums = [0,1,4,4,5,6,7]might become:
[4,5,6,7,0,1,4]if it was rotated4times.[0,1,4,4,5,6,7]if it was rotated7times.Notice that rotating an array
[a[0], a[1], a[2], ..., a[n-1]]1 time results in the array[a[n-1], a[0], a[1], a[2], ..., a[n-2]].Given the sorted rotated array
numsthat may contain duplicates, return the minimum element of this array.You must decrease the overall operation steps as much as possible.
解题思路:
用set()把多余的去掉后,直接min()求最小值。(不过并没有用到二分搜索……)
class Solution:
def findMin(self, nums: List[int]) -> int:
new_nums = min(list(set(nums)))
return new_nums
runtime:

参考36ms的sample solution:

不同之前简单的153做法在于当中值小于右值且大于左值时,右标左移一位。暂时不理解。看一下solution的解答。解答中说的是,当中值和右值一样大时,因为不确定最小值是在中值的左边还是右边,所以保险起见,就把右标左移了一位。再比较大小看看。这里不用担心有重复值,最后一步else就搞定。
重写了遍。
class Solution:
def findMin(self, nums: List[int]) -> int:
l, r = 0, len(nums)-1
while l<r:
m = (l+r)//2
if nums[m] > nums[r]: l = m + 1
elif nums[m] < nums[r]: r = m
else: r -= 1
return nums[r]
runtime:

#349 Intersection of Two Arrays
Given two integer arrays
nums1andnums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
解题思路:
谷歌搜到直接求两个list的intersection,可以直接对其中一个list用set(),然后对另一个list用.intersection() method。(好像也和二分搜索无关?为啥Leetcode会放在binary search这个版块?
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return set(nums1).intersection(nums2)
runtime:

sample solution说可以直接使用built-in的 & 来对两个set()进行 intersect。最后再list()输出。
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
runtime:

不过还是用intersection method更快。只要两步。sample用了4步。
6万+

被折叠的 条评论
为什么被折叠?



