题目如下:

spacer.gif图片.png

大概的意思是:给我们一个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.优化解法

    蛮力法虽然是我这种菜鸟的最爱,可惜不是面试官要的答案,还是不能将就的。想办法把时间复杂度将为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};    
    }
}