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"); // 没有找到符合条件的数,抛出异常
}

该算法的时间复杂度为 O(n),需要遍历整个数组一次。空间复杂度为 O(n),需要使用哈希表存储元素。

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

原文地址: https://www.cveoy.top/t/topic/lU5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录