clean C# O(n^2) hashtable


  • 0
    Y
    public class Solution {
        public int FourSumCount(int[] A, int[] B, int[] C, int[] D) {
          //like two sum
            Dictionary<int,int> hash=new Dictionary<int,int>();
            int n=A.Length;
            for(int i=0;i<n;i++)
            {
                for(int j=0;j<n;j++)
                {
                    if(hash.ContainsKey(C[i]+D[j]))
                        hash[C[i]+D[j]]++;
                    else
                        hash.Add(C[i]+D[j],1);
                }
            }
            int res=0;
            for(int i=0;i<n;i++)
            {
                for(int j=0;j<n;j++)
                {
                    if(hash.ContainsKey(0-A[i]-B[j]))
                      res+=hash[0-A[i]-B[j]];
                }
            }
            return res;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.