Created
September 8, 2017 17:34
-
-
Save jianminchen/1172402ff57a247449a448f64d33912a to your computer and use it in GitHub Desktop.
Leetcode 532 - pass leetcode 532 online judge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int FindPairs(int[] arr, int k) | |
{ | |
// your code goes hereif | |
if (arr == null || arr.Length == 0 || k < 0) | |
{ | |
return 0; | |
} | |
// assume that arr is not empty | |
var pairs = new List<int[]>(); // int[0] -> bigger value | |
var set = new HashSet<int>(); | |
var existing = new HashSet<int>(); | |
foreach (var number in arr) // 0, -1, -2 , 2, 1 | |
{ | |
var searchBigger = number + k; // 1 , 0, -1, 3, 2 | |
var searchSmaller = number - k; // -1, -2, -3, 1, 0 | |
if (set.Contains(searchBigger)) // true, 2 | |
{ | |
// add the pair | |
if (!existing.Contains(searchBigger)) | |
{ | |
pairs.Add(new int[] { searchBigger, number }); // (0, -1), (-1, -2), [2, 1] | |
existing.Add(searchBigger); | |
} | |
} | |
if (set.Contains(searchSmaller)) // -1=> true, | |
{ | |
// add the pair | |
if (!existing.Contains(number)) | |
{ | |
pairs.Add(new int[] { number, searchSmaller }); // -> [1, 0] | |
existing.Add(number); | |
} | |
} | |
set.Add(number); // {0, -1, -2, 2} | |
} | |
return pairs.Count; // | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment