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

前端 未结 5 2084
独厮守ぢ
独厮守ぢ 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:43

    If you can assume the numbers are positive, you can do this:

    1. Create a boolean array of 75 elements.
    2. Walk the list of 10,000,000 items. When you see one that's 75 or less:
      • check to see boolean arry has an entry at element 75 - that number. If it does, you found a match.
      • otherwise, set the nth entry of the boolean array.

    Example C#:

            var bits = new bool[75];
            foreach (var n in intArray)
            {
                if (n <= 75)
                {
                    var diff = 75 - n;
                    if (bits[diff - 1])
                    {
                        MessageBox.Show(string.Format("Found pair: {0} and {1}", n, diff));
                        break;
                    }
                    bits[n - 1] = true;
                }
            }
    

    But if the numbers in the array can be any valid integer, including negative numbers, you can do something like this:

            var set = new HashSet();
            foreach (var n in intArray)
            {
                if (n <= 75)
                {
                    var diff = 75 - n;
    
                    if (set.Contains(diff))
                    {
                        MessageBox.Show(string.Format("Found pair: {0} and {1}", n, diff));
                        break;
                    }
                    set.Add(n);
                }
            }
    

提交回复
热议问题