Created
August 20, 2020 11:36
-
-
Save AbhiAgarwal192/cff07d1e941b014ffd38f8717d4c4f87 to your computer and use it in GitHub Desktop.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int[] TwoSum(int[] nums, int target) { | |
//Get length of the array | |
int len = nums.Length; | |
//Create a dictionary of array elements | |
var map = new Dictionary<int,int>(); | |
for(int i=0;i<len;i++){ | |
if(map.ContainsKey(nums[i])){ | |
map[nums[i]] = map[nums[i]]+1; | |
} | |
else{ | |
map.Add(nums[i],1); | |
} | |
} | |
//Array to store output | |
int[] index = new int[2]; | |
bool found = false; | |
int num = 0; | |
for(int i=0;i<len;i++){ | |
num = target-nums[i]; | |
if(map.ContainsKey(num)){ | |
if( (num == nums[i]) && map[nums[i]]>=2 ){ | |
index[0] = i; | |
found = true; | |
break; | |
} | |
else if(num != nums[i]){ | |
index[0] = i; | |
found = true; | |
break; | |
} | |
} | |
} | |
if(found){ | |
for(int i=0;i<len;i++){ | |
if(i!=index[0] && nums[i] == num){ | |
index[1] = i; | |
break; | |
} | |
} | |
return index; | |
} | |
return new int[0]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment