zoukankan      html  css  js  c++  java
  • 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: [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:[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: [1, 3, 1, 5, 4], k = 0
    Output: 1
    Explanation: There is one 0-diff pair in the array, (1, 1).
    

    Note:

    1. The pairs (i, j) and (j, i) count as the same pair.
    2. The length of the array won't exceed 10,000.
    3. All the integers in the given input belong to the range: [-1e7, 1e7].

    链接:https://leetcode.com/problems/k-diff-pairs-in-an-array/#/description

    3/31/2017

    37%, 42ms

    注意输入负数时候返回0

    第6行可以去掉,第18行就不需要/2了。

     1 public class Solution {
     2     public int findPairs(int[] nums, int k) {
     3         if (k < 0) return 0;
     4         Map<Integer, Integer> a = new HashMap<Integer, Integer>();
     5         int count = 0;
     6         for (int i = 0; i < nums.length; i++) {
     7             a.put(nums[i], a.getOrDefault(nums[i], 0) + 1);
     8         }
     9         if (k == 0) {
    10             for (Map.Entry<Integer, Integer> e: a.entrySet()) {
    11                 if (e.getValue() > 1) count++;
    12             }
    13         } else {
    14             for (Map.Entry<Integer, Integer> e: a.entrySet()) {
    15                 if (a.containsKey(e.getKey() + k)) count++;
    16                 if (a.containsKey(e.getKey() - k)) count++;
    17             }
    18             count /= 2;
    19         }
    20         return count;
    21     }
    22 }

    其他人做法

    https://discuss.leetcode.com/category/683/k-diff-pairs-in-an-array

  • 相关阅读:
    NOI2005维修数列
    BZOJ1208 [HNOI2004]宠物收养所
    BZOJ3223 文艺平衡树
    BZOJ [JSOI2008]星球大战starwar
    BZOJ1013 [JSOI2008]球形空间产生器sphere
    小程序之底部tabBar
    es6
    vue.js安装
    模块打包工具webpack
    highchart
  • 原文地址:https://www.cnblogs.com/panini/p/6654341.html
Copyright © 2011-2022 走看看