C# - 2 cases: k == 0 use map, k > 0 use set


  • 0

    This problem would only require a set, you would not need to keep track of counts of number except of the case where k==0 where you need to be sure to only count the pair on the second instance of a number and thus you need to keep a count of each number.

        public int FindPairs(int[] nums, int k) 
        {
            int cnt = 0;
            
            if (k == 0)
            {
                Dictionary<int,int> map = new Dictionary<int,int>();
                foreach (int x in nums) 
                {
                    if (!map.ContainsKey(x)) map[x] = 0;
                    map[x]++;
                    if (map[x] == 2) cnt++; 
                }
            }
            else if (k > 0)
            {
                HashSet<int> set = new HashSet<int>();
                foreach (int x in nums)
                {
                    if (!set.Contains(x))
                    {
                        if (set.Contains(x+k)) cnt++;
                        if (set.Contains(x-k)) cnt++;
                        set.Add(x);
                    }
                }
            }
            
            return cnt;
        }
    

Log in to reply
 

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