-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14-1. Two Sum
More file actions
37 lines (34 loc) · 988 Bytes
/
Copy path14-1. Two Sum
File metadata and controls
37 lines (34 loc) · 988 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*class Solution {
public int[] twoSum(int[] nums, int target) {
int sum=0;
for (int i = 0; i < nums.length; i++){
for (int j = nums.length-1; j > 0; j--){
sum=nums[i]+nums[j];
if(sum==target){
return new int[] {i,j};
}
}
}
return null;
}
}*/
//2nd SOLUTION-OPTIMIZED
class Solution {
public int[] twoSum(int[] nums, int target) {
int pair[]=new int[2];
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
int result=target-nums[i];
if(map.get(result)!=null){
pair[0]=map.get(result);
pair[1]=i;
}
else{
map.put(nums[i],i);
}
}
return pair;
}
}
// In the map, keys and values are paired as key:value.and we can call only keys.
https://leetcode.com/problems/two-sum/