forked from mengli/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwo Sum.java
More file actions
66 lines (56 loc) · 1.78 KB
/
Two Sum.java
File metadata and controls
66 lines (56 loc) · 1.78 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
public class Solution {
public class Num {
private int value;
private int index;
public Num(int value, int index) {
super();
this.value = value;
this.index = index;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public int[] twoSum(int[] numbers, int target) {
Num[] newArray = new Num[numbers.length];
for (int i = 0; i < numbers.length; i++) {
newArray[i] = new Num(numbers[i], i);
}
Arrays.sort(newArray, new Comparator<Num>() {
public int compare(Num n1, Num n2) {
if (n1.getValue() == n2.getValue()) return 0;
if (n1.getValue() > n2.getValue()) return 1;
return -1;
}
});
int[] result = new int[2];
int i = 0, j = numbers.length - 1;
while (i < j) {
int tmp = newArray[i].getValue() + newArray[j].getValue();
if (tmp == target) {
result[0] = Math.min(newArray[i].getIndex() + 1, newArray[j].getIndex() + 1);
result[1] = Math.max(newArray[i].getIndex() + 1, newArray[j].getIndex() + 1);
break;
} else if (tmp > target) {
j--;
} else {
i++;
}
}
return result;
}
}