June 23, 2017

Write A C# Program to Determine If Any Two Integers In Array Sum to Given Integer


Write A C# Program to Determine If Any Two Integers In Array Sum to Given Integer?

How to find all pairs of elements in an integer array, whose sum is equal to a given number? 

ANS:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodingAlgorithm
{
    //Given an integer and an array of integers determine whether any two integers in the array sum to that integer.
    public static class TargetSum
    {
        //Brute force solution, O(n^2) time complexity
        public static bool TwoIntegersSumToTarget(int[] arr, int target)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                for (int k = 0; k < arr.Length; k++)
                {
                    if (i != k)
                    {
                        int sum = arr[i] + arr[k];
                        if (sum == target)
                            return true;
                    }
                }
            }
            return false;
        }
    }
}



Subscribe to get more Posts :