美文网首页
[easy][Array][Two-pointer]532. K

[easy][Array][Two-pointer]532. K

作者: 小双2510 | 来源:发表于2017-11-23 01:16 被阅读0次

    原题是:

    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
    

    相关文章

      网友评论

          本文标题:[easy][Array][Two-pointer]532. K

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