首页 > 学院 > 开发设计 > 正文

【Leetcode】532. K-diff Pairs in an Array

2019-11-06 07:14:53
字体:
来源:转载
供稿:网友

思路:

成对的值不分先后,所以先对nums进行排序。

用一个set存储出现过的值,用于后续判断是否某个值已经有值与其成对。

分为两种情况:

(1)k==0,即找出值相等的对数。

再用一个sameSet存储所有已成对的值,避免同一个值加入结果多次。只有sameSet中不含该值,且set中包含了该值,才能加入结果。

(2)k!=0,即找出差的绝对值为k的对数。

只有set中不包含该值但包含了该值-k,才能加入结果。

public class Solution {    public int findPairs(int[] nums, int k) {        int len = nums.length, result = 0;        Arrays.sort(nums);        Set<Integer> set = new HashSet<Integer>();        Set<Integer> sameSet = new HashSet<Integer>();        if (k != 0) {            for (int i = 0; i < len; i++) {                if (!set.contains(nums[i]) && set.contains(nums[i] - k))                     result++;                set.add(nums[i]);            }        }        else {            for (int i = 0; i < len; i++) {                if (!sameSet.contains(nums[i]) && set.contains(nums[i])) {                    result++;                    sameSet.add(nums[i]);                }                set.add(nums[i]);            }         }        return result;    } }Runtime:44ms


上一篇:UVA, 369 conbinations

下一篇:415. Add Strings

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表