您的位置:首页 > 大数据 > 人工智能

K-diff Pairs in an Array leetcode 532

2017-03-07 08:22 387 查看
题目大意:给定一个数组,从中取出差值绝对值为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
= (h.include? n) ? h
+ 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ruby leetcode 算法