题目以下:java
大概的意思是:给咱们一个Int型的数组和一个目标值,找出数组中两个值之和为目标值的元素位置;要求是每一个输入对应一个答案(即找到符合条件的元素直接返回结果就行,不用继续日后找,难度下降)而且相同的元素值不能用两次。面试
1.刚开始的思路: 数组
伟大而又万能的蛮力法,用两个for循环,很容易求解,时间复杂度为O(N^2),代码以下:数据结构
class Solution { public int[] twoSum(int[] nums, int target) { int[] res = new int[2]; for(int i = 0;i < nums.length;i++){ for(int j = i+1;j < nums.length;j++){ if((nums[i]+nums[j]) == target){ res[0] = i; res[1] = j; return res; } } } return res; } }
2.优化解法ide
蛮力法虽然是我这种菜鸟的最爱,惋惜不是面试官要的答案,仍是不能将就的。想办法把时间复杂度将为O(N)就很爽了啊,也就是把上面蛮力法中的一个for循环给去掉,怎么弄呢?蛮力法的思路是不断地进行a+b去匹配目标值c,既然目标值知道,那咱们固然能够选择c-b去匹配a。用一个for循环将c-b的值存在一个数据结构中,而后查找这个数据结构中是否含有a就行。那么问题来了,这个数据结构选什么呢:数组?栈?队列仍是HashMap?一看前面三种选择查找的时间复杂度仍是O(N),而HashMap查找的时间复杂度为O(1),那确定选HashMap,问题都搞定了,代码实现出来就OK:优化
public class TwoSumBter { public static int[] twosum(int[] num,int target){ int[] res = new int[2]; int len = num.length; //判断输入数组的大小 if(num == null || num.length<2){ res[0] = 0; res[1] = 0; return res; } //创建HashMap HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(); for(int i=0;i<len;i++){ //判断HashMap中是否含有目标数组中的数 if(hm.containsKey(num[i])){ res[0] = hm.get(num[i]); res[1] = i; return res; }else{ hm.put((target-num[i]), i); } } return new int[]{0,0}; } }