Two sum

By   Tewodros   Date Posted: Nov. 1, 2023  Hits: 424   Category:  Algorithm   Total Comment: 0             A+ A-


side

Find the indices of two numbers from a given list of numbers that adds up to a given target number 

Example

nums = 1,3,5,4

Target= 6

ans = 0,2

 

Example

nums = 3 , 4, 2

Target = 6

ans = 1, 2

 

Solution:

This problem can be solved using hashtable as follows:

We first throw target - nums(i) in to the hash table.

Then we will check if the hash table contains a(i) which is an indication that the pair exists that will make the target sum.

We also need to put an additional check that the current index is different from what we have stored in the hash table for current number:
i!= (int)ht[nums[i]] 

public class Solution {

    public int[] TwoSum(int[] nums, int target) {

        int [] result = new int[2];       

       

        Hashtable ht = new Hashtable();

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

        {

            if(!ht.Contains(nums[i]))

            {

                ht[target-nums[i]] = i;             

            }

        }


 

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

        {

            if(ht.Contains(nums[i]) && i!= (int)ht[nums[i]] )

            {        

                result[0]= i;

                result[1] = (int)ht[nums[i]];

                break;                 

            }

        }


 

     return result;

    }

}


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* ldavoa

Back to Top