• [LeetCode] 532. K-diff Pairs in an Array


    Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

    Example 1:

    Input: nums = [3,1,4,1,5], k = 2
    Output: 2
    Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
    Although we have two 1s in the input, we should only return the number of unique pairs.
    

    Example 2:

    Input: nums = [1,2,3,4,5], k = 1
    Output: 4
    Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
    

    Example 3:

    Input: nums = [1,3,1,5,4], k = 0
    Output: 1
    Explanation: There is one 0-diff pair in the array, (1, 1).
    

    Example 4:

    Input: nums = [1,2,4,4,3,3,0,9,2,3], k = 3
    Output: 2
    

    Example 5:

    Input: nums = [-1,-2,-3], k = 1
    Output: 2

    Constraints:

    • 1 <= nums.length <= 104
    • -107 <= nums[i] <= 107
    • 0 <= k <= 107

    数组中的K-diff数对。题意是给一个整数数组和一个整数K,请你求出数组中有多少对数字满足两个数字之间的差值是K。

    思路是用hashmap记录每个数字和他们出现的次数。再次遍历数组,也要分两种情况讨论

    • 如果K = 0,那么只要找到任何一个出现超过两次的数字,就res++
    • 如果K > 0,那么当遍历到num[i]的时候,就去看hashmap中是否有nums[i] + k,有则res++

    对于第二种情况,我第一次做的时候有试图去找nums[i] - k,后来发觉没必要。因为hashmap会遍历所有的key,所以结果不会丢失

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public int findPairs(int[] nums, int k) {
     3         // corner case
     4         if (nums == null || nums.length == 0) {
     5             return 0;
     6         }
     7 
     8         // normal case
     9         HashMap<Integer, Integer> map = new HashMap<>();
    10         int res = 0;
    11         for (int num : nums) {
    12             map.put(num, map.getOrDefault(num, 0) + 1);
    13         }
    14 
    15         for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    16             if (k == 0) {
    17                 if (entry.getValue() >= 2) {
    18                     res++;
    19                 }
    20             } else {
    21                 if (map.containsKey(entry.getKey() + k)) {
    22                     res++;
    23                 }
    24             }
    25         }
    26         return res;
    27     }
    28 }

    LeetCode 题目总结

  • 相关阅读:
    初识Mysql 连接器的收获(包含JDBC API最新文档)以及一些c++的有用技巧
    重拾 ”多项式“ 给我的启示
    vs2015下配置MySQL,使之能使用c++连接完美运行
    在CentOS上使用yum安装java
    CentOS 用yum安装中文输入法
    Redhat Linux RHEL5配置CentOS YUM更新源
    转:Linux下which、whereis、locate、find 命令的区别
    Centos 挂载NTFS格式的USB硬盘
    scp采用无密码在两台linux服务器之间传输数据
    转:Andriod studio技巧合集
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12784202.html
Copyright © 2020-2023  润新知