-
Notifications
You must be signed in to change notification settings - Fork 2
/
TwoSum.java
30 lines (26 loc) · 1.05 KB
/
TwoSum.java
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
package TwoSum;
public class Solution {
public int[] solution;
public int[] twoSum(int[] nums, int target) {
//using HashMap
HashMap<Integer,Integer> hashmap = new HashMap<Integer,Integer>();
//Put the number as "key", and its index as "value"
for(int i=0; i < nums.length; i++){
hashmap.put(nums[i], i);
}
//We are looking for another number that is equal to "target - nums[i]"
for(int i=0; i < nums.length; i++){
int another = target - nums[i];
if(hashmap.containsKey(another) && (int)hashmap.get(another) !=i){
//if we can find another_number and another_number is not itself
int another_index;
another_index = (int)hashmap.get(another); //get the index
solution = new int[2]; //for the two index (solution)
solution[0] = i;
solution [1] = another_index;
return solution;
}
}
return nums; //no solution
}
}