C# Solution with Binary Search


  • 0
    K
    public class Solution {
        public int[] Intersection(int[] nums1, int[] nums2) {
            
            Dictionary<int,int> map = new Dictionary<int,int>();
            if(nums1.Length == 0 || nums2.Length == 0)
            {
              return   map.Keys.ToArray();
            }
            
            Array.Sort(nums1);
            Array.Sort(nums2);
    
            foreach(int num in nums1)
            {
                if(BinarySearchValue(nums2, num))
                {
                    if(!map.ContainsKey(num))
                    {
                        map.Add(num,1);
                    }
                }
            }
          return  map.Keys.ToArray();
        }
        
        public bool BinarySearchValue(int[] nums2, int val)
        {
            int min=0;
            int max = nums2.Length - 1;
            
            while(min<=max)
            {
                int med = min+ (max - min)/2;
                
                if(nums2[med]==val)
                {
                    return true;
                }            
                else if(nums2[med]<val)
                {
                    min = med +1;
                }
                else if(nums2[med]>val)
                {
                    max = med -1;
                }
            }
            return false;
        }
    }
    
    

Log in to reply
 

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