辉乾

算法1

题目:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]


分析:这是我刚开始做算法题,刚看到题目有点无从下手的感觉,虽然在力扣上很简单,看到题目第一想法就是for循环,
然后仔细看后,不能重复利用这个数组的元素,就有点头疼了,然后想了下应该用Map,然后就写出了我的这个版本,

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for (int i=0;i<nums.length;i++){
            for (int t=0; t<i;t++){
                if (nums[i] == map.get(t)){
                    int[] tag = new int[2];
                    tag[0] = t;
                    tag[1] = i;
                    return tag;
                }
            }
            map.put(i,target -nums[i]);
        }
        return null;
    }
}
View Code

看到最好的方法是下面这种

方法三:一遍哈希表

事实证明,我们可以一次完成。在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。

如果它存在,那我们已经找到了对应解,并立即将其返回。

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}
View Code

刚开始,可能各个方面都有欠缺,想不到方法去处理。以后多练习。




posted on 2019-04-21 15:28  辉乾  阅读(89)  评论(0编辑  收藏  举报