题解:
import java.util.HashMap;
import java.util.Map;
public class Test {
//暴力解决法
public static int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
int[] indexs={0,0};
indexs[0]=i;
indexs[1]=j;
return indexs;
}
}
}
return null;
}
//哈希表解决发
public static int[] twoSump(int[] nums, int target) {
Map<Integer,Integer> hashtable=new HashMap<>();
for(int i=0;i<nums.length;++i){
if(hashtable.containsKey(target-nums[i])){
return new int[]{hashtable.get(target-nums[i]),i};
}
hashtable.put(nums[i],i);
}
return null;
}
//测试
public static void main(String[] args) {
int[] nums={2,4,5,7};
int target=9;
// int targets[]=twoSum(nums,target);
int targets[]=twoSump(nums,target);
for(int i:targets){
System.out.println(i);
}
}
}