Skip to content

Commit cfaf49b

Browse files
committed
Contributed in Two Sum problem
1 parent bb69473 commit cfaf49b

1 file changed

Lines changed: 19 additions & 12 deletions

File tree

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
1-
//solved using hashmap
2-
31
class Solution {
42
public int[] twoSum(int[] nums, int target) {
5-
Map <Integer, Integer> map = new HashMap<>();
3+
int arr[] = new int[2];
4+
Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
5+
for(int i = 0; i < nums.length; ++i) {
6+
mp.put(nums[i], i);
7+
}
68

7-
for(int i=0;i<=nums.length; i++) {
8-
int compliment = target - nums[i];
9-
10-
if(map.containsKey(compliment)) {
11-
return new int[] {map.get(compliment), i};
9+
for(int j = 0; j < nums.length; ++j) {
10+
int comp = target - nums[j];
11+
if(mp.containsKey(comp)) {
12+
int val = mp.get(comp);
13+
if(val == j) {
14+
continue;
15+
}
16+
else {
17+
arr[0] = j;
18+
arr[1] = val;
19+
break;
20+
}
1221
}
13-
14-
map.put(nums[i], i);
15-
}
16-
throw new IllegalArgumentException("No match found");
22+
}
23+
return arr;
1724
}
1825
}

0 commit comments

Comments
 (0)