美文网首页
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 数组题

    Summary Ranges 找到连续的值,使用一个格式将其打印出来。 来自讨论区 StefanPochmann ...

  • Lettcode 动态规划 medium

    Unique Paths II (Lettcode)一个机器人在 M * N 的二维数组中,机器人可以向下或向右移...

  • lettcode刷题之贪心

    leetcode刷题,使用python 1, 跳跃游戏 II —— 0045 贪心算法给定一个长度为 n 的 0...

  • lettcode 题目

    Valid Parentheses给定一个只包括'(',')','{','}','[',']'的字符串,判断字符串...

  • lettcode题目

    https://www.cnblogs.com/yuzhangcmu/tag/LeetCode/

  • lettcode sql

    +----+-------+--------+-----------+| Id | Name | Salary ...

  • 最长公共前缀 和 最大水量

    lettcode 题目求解 Python Longest Common Prefix给定一个字符串,返回其最长前缀...

  • lintcode 主元素(|、||、|||)

    三道题感觉是一个题给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的1/k。样例给出数组 [...

  • LeetCode 力扣 90. 子集 II

    题目描述(中等难度) 78题升级版,大家可以先做 78 题。给定一个数组,输出所有它的子数组。区别在于,这道题给定...

  • 编程题数组

    矩阵旋转90度 https://blog.csdn.net/qq_26525215/article/details...

网友评论

      本文标题:Lettcode 数组题

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