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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
解题思路
方法1、将每个值存到Map中个,其中key为值,value为其下标;遍历一下所有的数值x,查找target与x的差判断其是否在map中存在,存在则可以直接找到两个的下标。
因为map不能存储两个相同的数值,但数据可能存在有两个数值重复需要对map的value进行处理,将其存成字符串,后面再进行解析。因为map查找数据的复杂度为O(logn),所以整体的时间复杂度为O(nlogn)
方法2、当数据的数值不大的时候可以考虑定义一个大的数组,用空间换时间,即数组flagNum[i]=0,将数值的对应的数组的下标置为1,有多个就进行累加,这样查找的时间复杂度为O(1),整体的时间复杂度为O(n)
public int[] twoSum(int[] nums, int target) {
int result[] = new int[2];
int i = 0;
Map<Integer,String> numMap = new HashMap<Integer,String>();
for(i = 0; i < nums.length; i++){
if (!numMap.containsKey(nums[i])) {
numMap.put(nums[i], i+"");
}else{
String t = numMap.get(nums[i]);
numMap.put(nums[i], t+","+i);//该值有多个
}
}
Iterator its = numMap.entrySet().iterator();
while(its.hasNext()){
Map.Entry<Integer,String> entry = (Entry<Integer, String>) its.next();
int num = entry.getKey();
String indexStr[] = entry.getValue().split(",");
int distNum = target - num;
result[0] = Integer.parseInt(indexStr[0]);
if (distNum == num) {//判断是否有其他的该数字
if(indexStr.length > 1 ){
result[1] = Integer.parseInt(indexStr[1]);
break;
}
}else{
if (numMap.containsKey(distNum)) {
result[1] = Integer.parseInt(numMap.get(distNum));
break;
}
}
}
// System.out.println(result[0]+" "+result[1]);
return result;
}
目前研究于Spark与Hadoop,群QQ号:521066396(spark,hadoop交流群),欢迎加入共同学习,一起进步~