• [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 题目总结

  • 相关阅读:
    CORS跨域资源共享漏洞
    Linux Restricted Shell Bypass
    无情一点并没有错
    [机器学习]numpy broadcast shape 机制
    Chrome和IE的xss过滤器分析总结
    php使用substr中文乱码问题
    mac下自定义伪协议配置
    【转】前端黑魔法之远程控制地址栏
    Windows可信任路径代码执行漏洞
    小记一次mysql启动失败没有日志的处理
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12784202.html
Copyright © 2020-2023  润新知