Find if pair of elements with given sum exists in large integer array

前端 未结 5 2038
独厮守ぢ
独厮守ぢ 2021-01-15 07:45

I\'m having a integer array of 10 Million elements, how to write a function in C# which returns True if the array has a pair which sums up to 75.

My code is:

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-15 08:24

    This is a bucketing problem. You want buckets of 0s to pair with 75s, 1s to pair with 74s, etcetera. Bucketing is a Dictionary jobby. A Dictionary> gives you a result in O(n) amortized. If you only care about a bool result then a HashSet is good enough. You can't get better than O(n).

        static bool PairExists(int[] arr, int sum) {
            var set = new HashSet();
            foreach (int elem in arr) set.Add(elem);
            foreach (int elem in set)
                if (set.Contains(sum - elem)) return true;
            return false;
        }
    

    If the array is likely to contain the pair then you could consider testing after the Add() call, still O(n).

提交回复
热议问题