</pre><pre name="code" class="java"><p style="margin-top: 0px; margin-bottom: 20px; padding-top: 0px; padding-bottom: 0px; border: 0px; outline: 0px; font-size: 13px; vertical-align: baseline; font-family: 'Helvetica Neue', arial, sans-serif; line-height: 21px; background-color: transparent;"><span style="color: rgb(51, 51, 255);">Given an array of integers, find two numbers such that they add up to a specific target number.</span></p><p style="margin-top: 0px; margin-bottom: 20px; padding-top: 0px; padding-bottom: 0px; border: 0px; outline: 0px; font-size: 13px; vertical-align: baseline; font-family: 'Helvetica Neue', arial, sans-serif; line-height: 21px; background-color: transparent;"><span style="color: rgb(51, 51, 255);">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.</span></p><p style="margin-top: 0px; margin-bottom: 20px; padding-top: 0px; padding-bottom: 0px; border: 0px; outline: 0px; font-size: 13px; vertical-align: baseline; font-family: 'Helvetica Neue', arial, sans-serif; line-height: 21px; background-color: transparent;"><span style="color: rgb(51, 51, 255);">You may assume that each input would have exactly one solution.</span></p><p style="margin-top: 0px; margin-bottom: 20px; padding-top: 0px; padding-bottom: 0px; border: 0px; outline: 0px; font-size: 13px; vertical-align: baseline; line-height: 21px; font-family: monospace; background-color: transparent;"><span style="color: rgb(51, 51, 255);"><span style="margin: 0px; padding: 0px; border: 0px; outline: 0px; vertical-align: baseline; background-color: transparent;">Input:</span> numbers={2, 7, 11, 15}, target=9<br style="margin: 0px;" /><span style="margin: 0px; padding: 0px; border: 0px; outline: 0px; vertical-align: baseline; background-color: transparent;">Output:</span> index1=1, index2=2</span></p>#版本一
<span style="font-family: Arial, Helvetica, sans-serif;">import java.util.Hashtable;</span>
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int a[] = new int[2];
Hashtable <Integer,Integer> num = new Hashtable<Integer,Integer>();
for(int i=0; i < numbers.length; i++){
num.put(numbers[i],i);
}
for(int i=0; i < numbers.length; i++){
if(num.containsKey(target - numbers[i])){
int n = num.get(target - numbers[i]);
if(n == i){
continue;
}
else{
if(n < i){
a[0] = n + 1;
a[1] = i + 1;
}else{
a[0] = i + 1;
a[1] = n + 1;
}
break;
}
}
}
return a;
}
}
#版本二 在时间上差不多,但是计算机次数肯定要少
import java.util.Hashtable;
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int a[] = new int[2];
Hashtable <Integer,Integer> num = new Hashtable<Integer,Integer>();
for(int i=0; i < numbers.length; i++){
if(num.containsKey(numbers[i])){
a[0] = num.get(numbers[i]) + 1;
a[1] = i + 1;
break;
}
num.put(target - numbers[i],i);
}
return a;
}
}