-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
86 lines (74 loc) · 2.13 KB
/
TwoSum.java
File metadata and controls
86 lines (74 loc) · 2.13 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.easy.problems;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Hashtable;
/**
* 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
* @author hippo_flying
*
*/
class Pair implements Comparable<Pair>{
public int number;
public int idx;
public Pair(int number, int idx){
this.number = number;
this.idx = idx;
}
public int compareTo(Pair other){
return this.number - other.number;
}
}
public class TwoSum {
public static int[] twoSum(int[] numbers, int target) {
// int[] result=new int[2];
// Pair[] pairs=new Pair[numbers.length];
// for(int i=0;i<numbers.length;i++){
// pairs[i]=new Pair(numbers[i],i+1);
// }
// Arrays.sort(pairs);
// int head=0;
// int tail=numbers.length-1;
// while(head<tail){
// if(pairs[head].number+pairs[tail].number==target){
// if(pairs[head].idx<pairs[tail].idx){
// result[0]=pairs[head].idx;
// result[1]=pairs[tail].idx;
// }else{
// result[1]=pairs[head].idx;
// result[0]=pairs[tail].idx;
// }
// break;
// }else if(pairs[head].number+pairs[tail].number>target){
// tail--;
// }else{
// head++;
// }
// }
//
// return result;
//
//Hashtable×ö·¨
int result[] = new int[2];
Hashtable<Integer, Integer> queryTable = new Hashtable<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if(queryTable.containsKey(target-numbers[i])){
result[1]=i+1;
result[0]=queryTable.get(target-numbers[i]);
}else{
queryTable.put(numbers[i], i+1);
}
}
return result;
}
public static void main(String[] args){
DecimalFormat a = new DecimalFormat("0.00%");
String b=a.format(0.0036);
System.out.println(b);
}
}