Created
May 1, 2018 21:33
-
-
Save jianminchen/a305c0fb281d965e0de05fa856fa9960 to your computer and use it in GitHub Desktop.
Leetcode 18 4 sum - practice with hashmap prepared on visited elements only
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; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Leetcode18_4sum | |
{ | |
class Program | |
{ | |
/// <summary> | |
/// Leetcode 18: 4 sum | |
/// https://leetcode.com/problems/4sum/description/ | |
/// May 1, 2018 | |
/// </summary> | |
/// <param name="args"></param> | |
static void Main(string[] args) | |
{ | |
var quardruplets = FourSum(new int[]{3, 2, 1, 4, 6}, 12); | |
} | |
public static IList<IList<int>> FourSum(int[] numbers, int target) | |
{ | |
var quadruplets = new List<IList<int>>(); | |
if (numbers == null || numbers.Length == 0) | |
{ | |
return quadruplets; | |
} | |
Array.Sort(numbers); | |
var firstTwoNumbersSums = new Dictionary<int, IList<int[]>>(); | |
var quadrupletsUnique = new HashSet<string>(); | |
int length = numbers.Length; | |
for (int third = 0; third < length - 1; third++) | |
{ | |
var thirdNumber = numbers[third]; | |
for (int fourth = third + 1; fourth < length; fourth++) | |
{ | |
var fourthNumber = numbers[fourth]; | |
var lastTwoSum = thirdNumber + fourthNumber; | |
var search = target - lastTwoSum; | |
if (!firstTwoNumbersSums.ContainsKey(search)) | |
{ | |
continue; | |
} | |
foreach(var item in firstTwoNumbersSums[search]) | |
{ | |
var firstNumber = numbers[item[0]]; | |
var secondNumber = numbers[item[1]]; | |
var quadruplet = new int[] { firstNumber, secondNumber, thirdNumber, fourthNumber }; | |
var key = string.Join(",", quadruplet); | |
if (!quadrupletsUnique.Contains(key)) | |
{ | |
quadrupletsUnique.Add(key); | |
quadruplets.Add(new List<int>(new int[] { firstNumber, secondNumber, thirdNumber, fourthNumber })); | |
} | |
} | |
} | |
// It is time to add visited element into two sum dictionary. | |
// Argue that no need to add any two indexes smaller than third, why? | |
for (int firstId = 0; firstId < third; firstId++) | |
{ | |
var firstNumber = numbers[firstId]; | |
var firstTwoSum = firstNumber + thirdNumber; | |
var newItems = new int[] { firstId, third }; | |
if (!firstTwoNumbersSums.ContainsKey(firstTwoSum)) | |
{ | |
var items = new List<int[]>(); | |
firstTwoNumbersSums.Add(firstTwoSum, items); | |
} | |
firstTwoNumbersSums[firstTwoSum].Add(newItems); | |
} | |
} | |
return quadruplets; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment