问题是要从数组中找到两个数据,使得两数之和等于目标值,输出该两数的下标(从0开始)
方法一:
public static int[] twoSum_2(int[] num,int target ) {
int low ,high;
int temp;
for(int i = 0; i< num.length; i++){
low = i;
temp = target- num[i];
for(int j =i+1; j< num.length; j++){
if(temp == num[j]){
high = j;
return new int[]{low,high};
}
}
}
return null;
}
方法二:用hashmap减少查找时间
import java.util.HashMap;
import java.util.Scanner;
import javax.swing.text.NumberFormatter;
public class Solution {
public static int[] twoSum(int[] num,int target ) {
final HashMap<Integer,Integer> myMap = new HashMap<Integer, Integer>();
//int []result = new int[2];
for (int i = 0; i < num.length; i++) {
myMap.put( num[i],i);
}
for (int i = 0; i < num.length; i++) {
int v = myMap.get( target - num[i]);
if (v != 0 && v > i) {
return new int[]{i,v};
}
}
return null;
}
public static void main(String[] args) {
int num[] = new int[]{2,7,11,15};
Scanner scanner = new Scanner(System.in);
int target = scanner.nextInt();
int []array = twoSum(num, target);
System.out.print("[");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
//System.out.print("");
}
System.out.print("]");
}
}