企业开发网站公司搜狗推广
给定一个整数数组 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) | 需要有序数据或空间限制较宽松 |
推荐使用哈希表法,它在时间复杂度和代码简洁性上均为最优。