python dictionary count

  1. Longest Harmonious Subsequence
    We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
    Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
# version 1
def findLHS(self, A):
    count = collections.Counter(A)
    ans = 0
    for x in count:
        if x+1 in count:
            ans = max(ans, count[x] + count[x+1])
    return ans
# version 2
def findLHS(self, A):
    count = {}
    # more straightforward way to count
    for x in A:
        count[x] = count.get(x, 0) + 1
    ans = 0
    for x in count:
        if x+1 in count:
            ans = max(ans, count[x] + count[x+1])
    return ans
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容