- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtwoSum.java
More file actions
Latest commit
39 lines (37 loc) · 1.17 KB
/
Copy pathtwoSum.java
File metadata and controls
39 lines (37 loc) · 1.17 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
publicclassSolution {
classElement{
intval;
intindex;
Element(intval, intindex) {
this.val = val;
this.index = index;
}
}
publicint[] twoSum(int[] numbers, inttarget) {
int [] ret = newint[2];
if (numbers==null || numbers.length<2 ) {
returnret;
}
Element[] e = newElement[numbers.length];
for(inti=0;i<numbers.length;i++){
e[i]=newElement(numbers[i],i);
}
Arrays.sort(e, newComparator<Element>() { publicintcompare(Elementa, Elementb) {returna.val>b.val?1:(a.val==b.val?0:-1);}});
intbegin = 0;
intend = e.length - 1;
while(begin<end) {
if((e[begin].val + e[end].val)==target) {
ret[0] = Math.min(e[begin].index, e[end].index) + 1;
ret[1] = Math.max(e[begin].index, e[end].index) + 1;
returnret;
} else {
if((e[begin].val + e[end].val)>target) {
end--;
} else {
begin++;
}
}
}
returnret;
}
}