Leetcode日练笔记10 #154 #349 Find Minimum in Rotated Sorted Array II (Hard) & Intersection of Two Arrays

#154 Find Minimum in Rotated Sorted Array II (Hard)

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:

  • [4,5,6,7,0,1,4] if it was rotated 4 times.
  • [0,1,4,4,5,6,7] if it was rotated 7 times.

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 nums that 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 nums1 and nums2, 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步。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值