Skip to content

Commit d090c5f

Browse files
sourabhvarshney111Sourabh Varshney
andauthored
Added Two Sum Leetcode solution (dubesar#613)
Co-authored-by: Sourabh Varshney <sourabh.varshney@hotstar.com>
1 parent 7fc1b7d commit d090c5f

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
public int[] twoSum(int[] nums, int target) {
5+
int n=nums.length;
6+
Map<Integer,Integer> map=new HashMap<>();
7+
int[] result=new int[2];
8+
for(int i=0;i<n;i++){
9+
if(map.containsKey(target-nums[i])){
10+
result[1]=i;
11+
result[0]=map.get(target-nums[i]);
12+
return result;
13+
}
14+
map.put(nums[i],i);
15+
}
16+
return result;
17+
}
18+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
2+
3+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
4+
5+
You can return the answer in any order.
6+
7+
8+
9+
Example 1:
10+
11+
Input: nums = [2,7,11,15], target = 9
12+
Output: [0,1]
13+
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
14+
Example 2:
15+
16+
Input: nums = [3,2,4], target = 6
17+
Output: [1,2]
18+
Example 3:
19+
20+
Input: nums = [3,3], target = 6
21+
Output: [0,1]
22+
23+
24+
Constraints:
25+
26+
2 <= nums.length <= 104
27+
-109 <= nums[i] <= 109
28+
-109 <= target <= 109
29+
Only one valid answer exists.

0 commit comments

Comments
 (0)