Saturday, June 19, 2021

how to use hashtable to quickly find the sum of two numbers meet the criteria?

 if there is a number array, we want to find the indexs of two numbers adding together meet the give number.

for an example we have a number array {1, 3,  4,  5, 8} and given 8

the result should be 1 , 3


where is sample code to solve the above issue.

using System;

using System.Collections;

using System.Diagnostics.CodeAnalysis;


namespace hashmap

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Hello World!");


            int[] numarray = new int[7] { 1, 2, 3, 4 ,5, 6, 8};

            int[] resultArray = new int[2];

            int testNum = 7;

            Hashtable ht = new Hashtable();

            for (int i = 0; i < numarray.Length; i++) {

                int result = 7 - numarray[i];

                if (ht.ContainsKey(numarray[i]))

                {

                    resultArray[0] = i;

                    resultArray[1] = (int)ht[numarray[i]];

                }

                else {

                    ht.Add(result, i);

                }

            }

            Console.WriteLine("position at {0}  {1}", resultArray[0], resultArray[1]);

        }

    }

}


No comments:

Post a Comment