K-diff Pairs in an Array leetcode 532

题目大意:给定一个数组,从中取出差值绝对值为k的pair,pair不能重复。

题目分析:如果调用combination之类的函数,会造成实际上的算法复杂度为O(n^2),最后导致了TLE。因此改为直接统计数字在数组中出现的次数,然后根据 k 的值来进行不同的判断统计。

AC code(Ruby):

def find_pairs(nums, k)
    if k < 0 || nums.length < 2
        return 0
    end
    count = 0
    h = Hash.new
    nums.each {|n| h[n] = (h.include? n) ? h[n] + 1 : 1 }
    if k == 0
        h.each_value {|v| count += 1 if v > 1 }
    elsif k > 0
        h.each_key {|key| count += 1 if h.include? key + k }
    end
    count
end


你可能感兴趣的:(算法与面试)