Leetcode001——两数之和

111 阅读1分钟

一、题目

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例1

输入:nums = [2,7,11,15],target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9,返回 [0, 1] 。

示例2

输入:nums = [3,2,4],target = 6 输出:[1,2]

示例3

输入:nums = [3,3],target = 6

输出:[0,1]

二、思路

暴力解法:创建数组,遍历原数组,找到能够相加等于目标值的数,返回下标即可

HashMap解法:创建一个数组,再创建一个HashMap,遍历原数组,把值存入hashMap对象,如果下一次目标对象减去遍历到的

image-20220109114943927

三、代码实现

暴力解法:

public class Leetcode01 {
    public static void main(String[] args) {
        Leetcode01 leetcode01 = new Leetcode01();
        int[] sumS = new int[]{1,3,6,13,8,14};
        int[] results = leetcode01.twoSum(sumS, 9);
        System.out.println(Arrays.toString(results));
    }

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

HashMap解法:

public class Leetcode01 {
    public static void main(String[] args) {
        int[] nums = new int[]{10,3,5,6,8,9,2};
        System.out.println(Arrays.toString(twoSum(nums, 14)));
    }

    public static int[] twoSum(int[] nums, int target) {
        if (nums == null || nums.length < 2){
            return new int[]{-1,-1};
        }
        int[] res = new int[]{-1,-1};
        HashMap<Integer,Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])){
                res[0] = map.get(target - nums[i]);
                res[1] = i;
                break;
            }
            map.put(nums[i],i);
        }
        return res;
    }
}