zoukankan      html  css  js  c++  java
  • [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 题目总结

  • 相关阅读:
    HTTP的连接过程
    查看mysql数据库及表编码格式
    spring quartz 的定时器cronExpression表达式写法(转载)
    两种 js下载文件的步骤
    进制转换三(二进制、八进制、十进制、十六进制之间的转换)
    进制的转换二
    Tls版本
    读李笑来《把时间当做朋友》笔记
    postman批量编辑参数
    uml类关系常见图标的含义
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12784202.html
Copyright © 2011-2022 走看看