题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
必须按顺序,第二个比第一个大,返回位置的值
第一种方法: 暴力解法,两次遍历。要注意j+1,因为j比i大
public int[ ] twoSum(int[] nums, int target) {
int [ ] a = new int[2];
for(int i=0;i < nums.length ; i++){
for(int j=i+1;j<nums.length;j++){
if(target-nums[i]==nums[j]){
a[0]= i;
a[1] =j;
break;
}
}
}
return a;
}
第二种方法: 利用Hashmap,把key和value存进去,比较新存入的是否满足 target - 之前的。这样一次遍历就可以了。要注意的是,containsKey 有s而且K大写。
public int[] twoSum(int[] nums, int target) {
int [] a = new int[2];
Map <Integer,Integer> map = new HashMap<>();
for(int i = 0; i<nums.length;i++){
if(!map.containsKey(target-nums[i])){
map.put(nums[i],i);
}else{
a[0] = map.get(target-nums[i]);
a[1] = i;
break;
}
}
return a;
}