CSharp Solution using Array.Sort


  • 0
    V

    CSharp Solution using sort O (nlogn)

    public class Solution {
        public int[] Intersect(int[] a, int[] b) {
            var dict = new Dictionary<int, int>();
            Array.Sort(a);
            Array.Sort(b);
            int i = 0;
            int j = 0;
            int count = 0;
            while(i < a.Length && j < b.Length){
                if(a[i]<b[j]){
                    i++;
                }else if(a[i] >b[j]){
                    j++;
                }else{
                    
                    if(dict.ContainsKey(a[i])){
                        dict[a[i]]+=1;
                    }else{
                        dict.Add(a[i], 1);
                    }
                    count++;
                    i++;
                    j++;
                }
            }
            
            int k = 0;
            int[] result = new int[count];
            foreach(var item in dict){
                int c = item.Value;
                while(c > 0)   {
                    result[k] = item.Key;
                    c--;
                    k++;
                }
            }
            
            return result;
        }
    }
    

Log in to reply
 

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