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

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

    You can do a brute force search.

    public bool hasPairOf(int[] a, int sum)
    {
       for(int i=0; i < a.length-1; i++)
       {
          if(a[i]+a[i+1] == sum)
             return true;
       }
       return false;
    }
    

    Alternatively, you could create an enumerator and use LINQ.

    public static IEnumerate toSums(this int[] a)
    {
       for(int i=0; i < a.length-1; i++)
       {
          yield return a[i]+a[i+1];
       }
    }
    

    Now you can do the following.

    a.toSums().Any(pair=>pair == 75);
    

    Both should have the same performance. If you ask why? that's because C# will only execute the enumerator until the Any condition is true. The toSums function uses the yield keyword to create an enumerator that is only executed when it is evaluated.

    EDIT:

    To find any pair of values in an array that sum to 75 and not just adjacent. I would do it using nothing but LINQ for easier reading.

    function bool hasPairOf(int[] a, int sum)
    {
        var nums = a.Where(val=>val <= sum)
                    .Select((v,i)=>new{value=v,index=i})
                    .ToArray();
    
        return (from a1 in nums
                from a2 in nums
                where a1.index != a2.index
                      && a1.value+a2.value == sum
                select true).FirstOrDefault();
    }
    

提交回复
热议问题