leetCode——第一题:两数之和

题目:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

思路:

利用双重循环,依次将两个数相加判断是否等于目标值,如果是,保存下标。

代码:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] re = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for(int j = i+1;jif(nums[i] + nums[j] == target) {
                    re[0] = i;
                    re[1] = j;
                }
            }
        }
        return re; 
    }
    //使用HashMap,将值和下标存到map中
    public static int[] twoSum1(int[] nums, int target) {
        HashMap m = new HashMap();
        int[] re = new int[2];
        for (int i = 0; i < nums.length; i++) {
            if(m.containsKey(target - nums[i])) {
                re[0] = i;
                re[1] = m.get(target-nums[i]);
                break;
            }
            m.put(nums[i], i);
        }
        return re;
    }
}

说明

小菜鸟一只,大佬走开。不知道有没有什么更好的方法。也没找。看到文章乐于分享的小伙伴,感谢评论分享更好的方法。

你可能感兴趣的:(leetCode,java,两数之和,leetCode,第一题)