[easy][Array][Two-pointer]532. K-diff Pairs in an Array

原题是:

Screen Shot 2017-11-22 at 12.14.12 PM.png

思路是:

两指针。
要注意的是K为0,和为负数的corner case。
Python里list去重的方法,我经常使用:list(set(nums))

代码是:

class Solution:
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k < 0 :
            return 0
        elif k != 0:
            noDup = list(set(nums))
            noDup = sorted(noDup)
            cnt, i ,j = 0, 0, 1
            while i < len(noDup) and j < len(noDup):
                if noDup[j] - noDup[i] == k:
                    cnt += 1
                    i += 1
                    j += 1
                elif noDup[j] - noDup[i] > k:
                    i += 1
                else:
                    j += 1
        else:
            nums = sorted(nums)
            candidate = []
            cnt = 0
            for i in range(len(nums)):
                if i < len(nums)-1 and nums[i] == nums[i+1]:
                    candidate.append(nums[i])
            cnt = len(list(set(candidate)))
        
        return cnt
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • 1. Two Sum 用hash可以得到O(n)时间的解法,用python中的enumerate函数,可以获得元素...
    Morphiaaa阅读 472评论 0 0
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 17,984评论 2 36
  • * Always remember to check the quality/availability of th...
    Morphiaaa阅读 746评论 0 0
  • 天上掉下个林妹妹 却只为了还这一世的泪水 大观园里的痴望眼 却只看见大地一片白茫茫 春去,林妹妹在东风里葬花魂 然...
    胡不度阅读 394评论 1 3