Skip to content

Commit 2d987c5

Browse files
committed
Chapter 04 section 04 Java codes added.
1 parent da0674b commit 2d987c5

File tree

1 file changed

+5
-7
lines changed

1 file changed

+5
-7
lines changed

04-Using-Hash-Table/Course Code (Java)/04-Two-Sum/src/Solution2.java

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,11 @@ public int[] twoSum(int[] nums, int target) {
2121

2222
for(int i = 0 ; i < nums.length; i ++){
2323

24-
if(record.containsKey(target - nums[i]))
25-
if(record.get(target - nums[i]) != i){
26-
int[] res = {i, record.get(target - nums[i])};
27-
return res;
28-
}
29-
30-
record.put(nums[i], i);
24+
Integer index = record.get(target - nums[i]);
25+
if(index != null && index != i){
26+
int[] res = {i, index};
27+
return res;
28+
}
3129
}
3230

3331
throw new IllegalStateException("the input has no solution");

0 commit comments

Comments
 (0)