Created
August 19, 2017 05:36
-
-
Save jianminchen/426c009f3a9de577a1180a60e9a44dd6 to your computer and use it in GitHub Desktop.
Leetcode 532 - fix the bug after the practice
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
using System; | |
using System.Collections.Generic; | |
class Solution | |
{ | |
// -2, -1, 0, 1, 2 k = 2 | |
// [-2, 0], [-1, 1], [0, 2] | |
// -2, -1 1 < 2, move right pointer, | |
public static int[,] FindPairsWithGivenDifference(int[] arr, int k) | |
{ | |
// your code goes here | |
if (arr == null || arr.Length == 0 || k <= 0) | |
{ | |
return new int[0, 0]; | |
} | |
Array.Sort(arr); // ascending order | |
var pairs = new List<int[]>(); | |
var length = arr.Length; // 5 | |
var left = 0; | |
var leftValue = arr[0]; //-2 | |
for (int i = 1; i < length; ) // remove i++ after mocking | |
{ | |
var current = arr[i]; // -1, 0, 1 | |
leftValue = (left < length) ? arr[left] : leftValue; // possible issue | |
if (left == length) | |
{ | |
break; | |
} | |
var difference = current - leftValue; // 1, 2 | |
var isEqual = difference == k; | |
var isSmaller = difference < k; // 1 < 2 | |
var isBigger = difference > k; | |
if (isEqual) | |
{ | |
pairs.Add(new int[] { current, leftValue }); // [-2, 0] | |
// reset left | |
left++; // 1 | |
i++; // added after mocking | |
} | |
else if (isSmaller) | |
{ | |
i++; // added after mocking | |
continue; | |
} | |
else if (isBigger) | |
{ | |
left++; | |
} | |
} | |
var size = pairs.Count; | |
var result = new int[size, 2]; | |
int index = 0; | |
foreach (int[] item in pairs) | |
{ | |
result[index, 0] = item[0]; | |
result[index, 1] = item[1]; | |
index++; | |
} | |
return result; | |
} | |
static void Main(string[] args) | |
{ | |
var result = FindPairsWithGivenDifference(new int[] { 1, 5, 11, 7 }, 4); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fb4953e