算法2 Two Sum

来源:互联网 发布:锦瑟 priest 知乎 编辑:程序博客网 时间:2024/06/11 14:00

题目:给出一个数组,再给定一个目标数,求出当数组中的两个数之和等于目标数时,这个两个数的索引?
例:一个数组为int[] a= [1,2,3,4,5] ,目标值为 target=8
当a[2]+a[4]=8,即索引为2,4

思路:依题可知,对数组进行取值加和比较,第一次循环取出一个数,第二次循环取出其它数与之相加,判断它们的和是否等于目标数。等于即返回两个索引值。
方法一

public int[] twoSum(int[] nums, int target) {int[] index = new int[2];    index[0]=-1;    index[1]=-1;    for (int i = 0; i < nums.length; i++) {        for (int j = i + 1; j < nums.length; j++) {            if (nums[j] == target - nums[i]) {                index[0]=i;                index[1]=j;                return index;            }        }    }    return index;}

感觉方式很简单,去论坛里找了找,发现了更好的方法 ,借此分享出来
方法二
思路 建个map,将数组之前的所有元素放到key里,value是相应的索引值。通过目标值减去当前数组元素来和map中的key进行比较,将时间复杂度O(n²)降到O(n)
代码

public int[] twoSum2(int[] numbers, int target) {    int[] result = new int[2];    Map<Integer, Integer> map = new HashMap<Integer, Integer>();    for (int i = 0; i < numbers.length; i++) {        //这里用了target - numbers[i],如果map里有,就直接找到了两个答案        if (map.containsKey(target - numbers[i])) {            result[1] = i ;            //通过Map的get方法得到标号,这里得到的是两个数中遍前面的数,因此给result[0]            result[0] = map.get(target - numbers[i]);            //返回正确结果            return result;        }        map.put(numbers[i], i);    }    return result;}
原创粉丝点击