-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
34 lines (31 loc) · 869 Bytes
/
TwoSum.java
File metadata and controls
34 lines (31 loc) · 869 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
import java.util.Arrays;
/*
* https://leetcode.com/problems/two-sum/
*/
class TwoSum {
public int[] twoSum(int[] nums, int target) {
int size = nums.length;
int[] diff = new int[size];
int i, index = -1;
for (i = 0 ; i < size ; i++) {
int num = nums[i];
index = index(diff, num, i);
if (index != -1) {
break;
}
diff[i] = target - num;
}
return new int[]{index,i};
}
private int index(int[] diff, int num, int maxIndex) {
for (int i = 0 ; i < maxIndex ; i++) {
if (diff[i] == num) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new TwoSum().twoSum(new int[]{2,7,11,15}, 9))); //[0,1]
}
}