题解 | #两数之和#
两数之和
http://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
import java.util.*;
public class Solution {
/**
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] numbers, int target) {
if(numbers.length < 2 || target < 0 || numbers.length > 100000 || target > 1000000000) return null;
Map<Integer,Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
//取出满足条件的下标
for(int i = 0;i < numbers.length; i++){
if(map.containsKey(target - numbers[i])){
list.add(map.get(target - numbers[i]) + 1);
list.add(i+1);
}else{
map.put(numbers[i],i);
}
}
int [] s = new int[list.size()];
for(int i=0;i<list.size();i++){
s[i] = list.get(i);
}
return s;
}
}