Skip to content

Instantly share code, notes, and snippets.

@svaza
Created April 15, 2022 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svaza/02c3d3836daca26adb179dd5c097b944 to your computer and use it in GitHub Desktop.
Save svaza/02c3d3836daca26adb179dd5c097b944 to your computer and use it in GitHub Desktop.
3 sum leetcode
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