每天一道面试题-两数之和

给定一个整数数组 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]

Java实现(哈希表法)

import java.util.HashMap;
import java.util.Map;

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

其他方法分析

1. 暴力法(双重循环)
public int[] twoSumBruteForce(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] == target) {
                return new int[]{i, j};
            }
        }
    }
    throw new IllegalArgumentException("No solution found");
}
  • 时间复杂度:O(n²),遍历所有可能的元素对。
  • 空间复杂度:O(1),无需额外存储。
  • 缺点:效率低,不适用于大规模数据。

2. 排序 + 双指针法
import java.util.Arrays;

public int[] twoSumWithSorting(int[] nums, int target) {
    int[][] sorted = new int[nums.length][2];
    for (int i = 0; i < nums.length; i++) {
        sorted[i][0] = nums[i];
        sorted[i][1] = i;
    }
    Arrays.sort(sorted, (a, b) -> Integer.compare(a[0], b[0]));
    
    int left = 0, right = nums.length - 1;
    while (left < right) {
        int sum = sorted[left][0] + sorted[right][0];
        if (sum == target) {
            return new int[]{sorted[left][1], sorted[right][1]};
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    throw new IllegalArgumentException("No solution found");
}
  • 时间复杂度:O(n log n),排序占主导。
  • 空间复杂度:O(n),需存储原始索引。
  • 缺点:需额外空间存储索引,且会破坏原始数组的顺序。

方法对比

方法时间复杂度空间复杂度适用场景
哈希表法O(n)O(n)通用场景,最优解
暴力法O(n²)O(1)数据量极小
排序双指针O(n log n)O(n)需要有序数据或空间限制较宽松

推荐使用哈希表法,它在时间复杂度和代码简洁性上均为最优。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值