LeetCode 算法@001 -Two Sum

问题陈述:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

解决思路:

1.爆破法

使用两个嵌套for循环一对一求和与目标值判断,时间复杂度为O(n^2)

2.哈希表

将int数组存入hashMap,key为数值,value为其坐标.第一层遍历时,可以用n(1)的时间复杂度找到是否存在对应的第二个数。这样就将爆破法里面的第二层for循环的复杂度降低至O(1),总的时间复杂度降至O(n).

 

Java代码:

import java.util.HashMap;
public class twosum {
public static void main(String[] args){
int[] a={3,2,4};
int target=6;
int[] x=twoSum(a,target);
for(int y:x){System.out.println(y);}
}
public static int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map =new HashMap<Integer,Integer>();
int numLen = nums.length;
int[] res=new int[2];
for(int j=0;j<numLen;j++){
map.put(nums[j],j+1);
}
for(int i=0;i<numLen;i++){
int findIndex = target-nums[i];
if(map.containsKey(findIndex)&&map.get(findIndex)!=i+1) {
int foundIndex = map.get(findIndex);
if(foundIndex<(i+1)){res[0]=foundIndex;res[1]=i+1;}
else{res[1]=foundIndex;res[0]=i+1;}
break;
}
}
return res;
}
}