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

你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。

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

方法一:暴力枚举

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // 暴力枚举
        int[] res = new int[2];
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                if (nums[i] + nums[j] == target) {
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return new int[0];
    }
}

方法二:HashMap

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // hashMap
        Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (hashMap.containsKey(nums[i])) {
                // 如果 hashMap 中已经有这个补数,证明遍历了
                return new int[]{i, hashMap.get(nums[i])};
            }
            // put(补数,index)
            hashMap.put(target-nums[i], i);
        }
        return new int[0];
    }
}
posted on 2025-07-09 00:10  caoshikui  阅读(5)  评论(0)    收藏  举报