LeetCode刷题【Array】 K-diff Pairs in an Array
来源:互联网 发布:sql2005数据库下载 编辑:程序博客网 时间:2024/06/08 17:18
题目:
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 = 2Output: 2Explanation: 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 = 1Output: 4Explanation: 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 = 0Output: 1Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
- The pairs (i, j) and (j, i) count as the same pair.
- The length of the array won't exceed 10,000.
- All the integers in the given input belong to the range: [-1e7, 1e7].
public class Solution { public int findPairs(int[] nums, int k) { if (nums == null || nums.length == 0 || k < 0) return 0; Map<Integer, Integer> map = new HashMap<>(); int count = 0; for (int i : nums) { map.put(i, map.getOrDefault(i, 0) + 1); } for (Map.Entry<Integer, Integer> entry : map.entrySet()) { if (k == 0) { //count how many elements in the array that appear more than twice. if (entry.getValue() >= 2) { count++; } } else { if (map.containsKey(entry.getKey() + k)) { count++; } } } return count; }}
参考:
【1】https://leetcode.com/
0 0
- LeetCode刷题【Array】 K-diff Pairs in an Array
- LeetCode K-diff Pairs in an Array
- LeetCode : K-diff Pairs in an Array
- leetCode-K-diff Pairs in an Array
- 【Leetcode】532. K-diff Pairs in an Array
- 532. K-diff Pairs in an Array ------Leetcode
- K-diff Pairs in an Array leetcode 532
- 【leetcode】532. K-diff Pairs in an Array
- [Leetcode]532. K-diff Pairs in an Array
- [LeetCode]532. K-diff Pairs in an Array
- Leetcode 532 K-diff Pairs in an Array
- [leetcode]-532 K-diff Pairs in an Array
- LeetCode 532. K-diff Pairs in an Array
- leetcode题解-532. K-diff Pairs in an Array
- LeetCode 532. K-diff Pairs in an Array
- [LeetCode]532. K-diff Pairs in an Array
- 20170605-leetcode-532-K-diff Pairs in an Array
- [leetcode]: 532. K-diff Pairs in an Array
- Golang操作数据库
- 二项堆
- openwrt添加 删除tab标签元素
- Linux curl命令详解
- 操作系统概念 -第七版-重要概念的理解-(56-63)
- LeetCode刷题【Array】 K-diff Pairs in an Array
- 去掉button ios默认样式
- 打印斐波那契数列的前三十个数中所有的质数,并统计个数。
- cmake项目所出现的问题
- 有关使用Maven常见问题总结(Eclipse中使用Maven、Maven项目部署到tomcat等问题)
- 一台电脑多个jdk环境解决方案
- Hibernate与Jpa的关系
- ant中的build.xml详细配置
- 程序员的十层楼