AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Saturday 10 December 2022

DSA Problem Solution: Two Sum




Given an unsorted integer array, find a pair with the given sum in it. 

 Input : array[] = [7, 8, 2, 5, 3, 1], target = 10 
Output: (8, 2) or (7, 3)

If no pair with the given sum exists, the solution should return the pair (-1, -1). 
Input : array[] = [5, 6, 2, 8, 1, 9], target = 12 Output: (-1, -1)


Solution c#:


public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        //var outarray= new int[2];
        Dictionary<int,int> map = new  Dictionary<int,int>();
        for(int i=0;i<nums.Count();i++)
        {
            map[nums[i]] = i;
        }
       
        for(int i=0;i<nums.Count();i++)
        {
            int findinmap = target-nums[i];
            if(map.ContainsKey(findinmap))
            {
                int index = map[findinmap];
                if(index !=i){
                return new int[]{i, index};
                }
            }        
        }
       
        return new int[]{-1, -1};
    }
}

Video Tutorial: 


0 comments :

Post a Comment

  • Popular Posts
  • Comments