美文网首页
Lettcode 数组题

Lettcode 数组题

作者: vckah | 来源:发表于2018-07-22 23:32 被阅读0次
    • Summary Ranges
    Input:  [0,1,2,4,5,7]
    Output: ["0->2","4->5","7"]
    Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
    

    找到连续的值,使用一个格式将其打印出来。

    def summaryRanges(nums):
        ranges, r = [], []
        for n in nums:
            if n-1 not in r:
                r = []
                ranges += r,
            r[1:] = n,
        return ['->'.join(map(str, r)) for r in ranges]
    

    来自讨论区 StefanPochmann
    的答案。这个人是个大牛,经常看见他不一样的思路,运用了 Python的各种 trick。
    例如本例中的 r[1:] = n,,注意逗号,如果没有逗号,则赋值是不成功的。还有 r += [],,直接 + 一个列表不会成功。还可以这么玩。当然了如果要显示所有数字,那么直接将 r[1:] += n, 变化一下即可。

    • Majority Element II
    Input: [1,1,1,3,3,2,2,2]
    Output: [1,2]
    

    找到一个数组中出现次数大于 n/3 的数。n 为数组长度。

    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        from collections import Counter
        ctr = Counter()
        for n in nums:
            ctr[n] += 1
            if len(ctr) == 3:
                ctr -= Counter(set(ctr))
        return [n for n in ctr if nums.count(n) > len(nums)/3]
    

    代码依旧来自于上面那位大牛,可以看到这里使用了 Counter 这个对象。值得仔细看看。

    相关文章

      网友评论

          本文标题:Lettcode 数组题

          本文链接:https://www.haomeiwen.com/subject/rfilmftx.html