
问题
给定一个整数数组和一个整数 k, 你需要在数组里找到不同的 k-diff 数对。这里将 k-diff 数对定义为一个整数对 (i, j), 其中 i 和 j 都是数组中的数字,且两数之差的绝对值是 k.
输入: [3, 1, 4, 1, 5], k = 2
输出: 2
解释: 数组中有两个 2-diff 数对, (1, 3) 和 (3, 5)。尽管数组中有两个1,但我们只应返回不同的数对的数量。
输入:[1, 2, 3, 4, 5], k = 1
输出: 4
解释: 数组中有四个 1-diff 数对, (1, 2), (2, 3), (3, 4) 和 (4, 5)。
输入: [1, 3, 1, 5, 4], k = 0
输出: 1
解释: 数组中只有一个 0-diff 数对,(1, 1)。
注意:
数对 (i, j) 和数对 (j, i) 被算作同一数对。
数组的长度不超过10,000。
所有输入的整数的范围在 [-1e7, 1e7]。
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.
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.
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).
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: 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 Program { public static void Main(string[] args) { int[] nums = null; nums = new int[] { 3, 1, 4, 1, 5 }; var res = FindPairs(nums, 2); Console.WriteLine(res); Console.ReadKey(); } private static int FindPairs(int[] nums, int k) { if(k < 0) return 0; var set1 = new HashSet<int>(); var set2 = new HashSet<int>(); for(int i = 0; i < nums.Length; i++) { //包含+k时直接添加到set2 if(set1.Contains(nums[i] + k)) { set2.Add(nums[i]); } //包含-k时直接添加到set2 if(set1.Contains(nums[i] - k)) { set2.Add(nums[i] - k); } //把所有值存入set1 set1.Add(nums[i]); } //返回2中的数量即为结果 return set2.Count(); } }
以上给出1种算法实现,以下是这个案例的输出结果:
2
分析:
显而易见,以上算法的时间复杂度为: 。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/3716。
评论列表(1条)
[…] 该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflyin… […]