|
| 1 | +/* ============================================================================== |
| 2 | + * 功能描述:FindPairsSln |
| 3 | + * 创 建 者:gz |
| 4 | + * 创建日期:2017/5/3 16:01:15 |
| 5 | + * ==============================================================================*/ |
| 6 | +using System; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.Linq; |
| 9 | +using System.Text; |
| 10 | + |
| 11 | +namespace Array.Lib |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// FindPairsSln |
| 15 | + /// </summary> |
| 16 | + |
| 17 | + // Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. |
| 18 | + // 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. |
| 19 | + |
| 20 | + //Example 1: |
| 21 | + //Input: [3, 1, 4, 1, 5], k = 2 |
| 22 | + //Output: 2 |
| 23 | + //Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). |
| 24 | + //Although we have two 1s in the input, we should only return the number of unique pairs. |
| 25 | + //Example 2: |
| 26 | + //Input:[1, 2, 3, 4, 5], k = 1 |
| 27 | + //Output: 4 |
| 28 | + //Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). |
| 29 | + //Example 3: |
| 30 | + //Input: [1, 3, 1, 5, 4], k = 0 |
| 31 | + //Output: 1 |
| 32 | + //Explanation: There is one 0-diff pair in the array, (1, 1). |
| 33 | + public class FindPairsSln |
| 34 | + { |
| 35 | + public int FindPairs(int[] nums, int k) |
| 36 | + { |
| 37 | + int sum = 0; |
| 38 | + if (nums.Length == 0 || nums.Length == 1) return 0; |
| 39 | + System.Array.Sort(nums); |
| 40 | + for (int i = 0; i < nums.Length; i++) |
| 41 | + { |
| 42 | + bool eql = false; |
| 43 | + for (int j = i + 1; j < nums.Length; j++) |
| 44 | + { |
| 45 | + while (j < nums.Length && nums[j] == nums[i]) |
| 46 | + { |
| 47 | + j++; |
| 48 | + eql = true; |
| 49 | + } |
| 50 | + if (eql) //找到了相等元素 |
| 51 | + { |
| 52 | + i = j - 1; //j-1>i=0 //i等于某一块相等元素的末端点 |
| 53 | + if (k == 0) |
| 54 | + { |
| 55 | + sum++; |
| 56 | + break; |
| 57 | + } |
| 58 | + eql = false; |
| 59 | + } |
| 60 | + while (j + 1 < nums.Length && nums[j + 1] == nums[j]) |
| 61 | + j++; //j等于后一块相等元素的末端点 |
| 62 | + if (j < nums.Length && nums[j] - nums[i] > k) // |
| 63 | + break; |
| 64 | + if (j < nums.Length && nums[j] - nums[i] == k) |
| 65 | + sum++; |
| 66 | + } |
| 67 | + } |
| 68 | + return sum; |
| 69 | + } |
| 70 | + |
| 71 | + } |
| 72 | +} |
0 commit comments