Created
April 15, 2022 03:31
-
-
Save svaza/02c3d3836daca26adb179dd5c097b944 to your computer and use it in GitHub Desktop.
3 sum leetcode
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.Collections.Generic; | |
public class Solution { | |
public IList<IList<int>> ThreeSum(int[] nums) { | |
var tripletsCollection = new List<IList<int>>(nums.Length); | |
var tripletSet = new HashSet<string>(nums.Length); | |
var numOccurance = new Dictionary<int, HashSet<int>>(nums.Length); | |
for(int i = 0; i < nums.Length; i++) | |
AddNumOccurance(numOccurance, nums[i], i); | |
if(nums.Length < 3) return tripletsCollection; | |
for(int i = 0; i < nums.Length; i++) | |
{ | |
for(int j = i+1; j < nums.Length; j++) | |
{ | |
var z = (nums[i]+nums[j]) * -1; | |
if(numOccurance.ContainsKey(z)) | |
{ | |
var zSet = numOccurance[z]; | |
int cntr = 0; | |
if(zSet.Contains(i)) cntr++; | |
if(zSet.Contains(j)) cntr++; | |
if((zSet.Count - cntr) <= 0) continue; | |
var possibleTriplet = new List<int>() { nums[i], nums[j], z}; | |
possibleTriplet.Sort(); | |
var tripletHash = $"{possibleTriplet[0]}.{possibleTriplet[1]}.{possibleTriplet[2]}"; | |
if(tripletSet.Contains(tripletHash)) continue; | |
tripletsCollection.Add(possibleTriplet); | |
tripletSet.Add(tripletHash); | |
} | |
} | |
} | |
return tripletsCollection; | |
} | |
private void AddNumOccurance(Dictionary<int, HashSet<int>> dict, int num, int i) | |
{ | |
if(!dict.ContainsKey(num)) | |
dict.Add(num, new HashSet<int>() { i }); | |
else dict[num].Add(i); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment