题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路
常见的解题思路有以下两种:
暴力法:使用两层循环枚举每一对数字,检查其和是否为目标值。时间复杂度为 O(n^2)。
哈希表法:在遍历数组的同时,利用哈希表记录已经访问过的元素及其索引,从而在 O(1) 时间复杂度内检查是否存在目标值与当前元素的差值对应的元素。时间复杂度为 O(n)。
接下来,我们分别使用 Java, Python 和 Golang 实现这两种解法。
一. Java 实现
暴力法
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 two sum solution");
}
哈希表法
import java.util.HashMap;
import java.util.Map;
public int[] twoSumHashMap(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");
}
二. Python 实现
暴力法
def twoSumBruteForce(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
raise ValueError("No two sum solution")
哈希表法
def twoSumHashMap(nums, target):
hashmap = {}
for i, num in enumerate(nums):
complement = target - num
if complement in hashmap:
return [hashmap[complement], i]
hashmap[num] = i
raise ValueError("No two sum solution")
三. Golang 实现
暴力法
func twoSumBruteForce(nums []int, target int) []int {
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
if nums[i]+nums[j] == target {
return []int{i, j}
}
}
}
panic("No two sum solution")
}
哈希表法
func twoSumHashMap(nums []int, target int) []int {
hashmap := make(map[int]int)
for i, num := range nums {
complement := target - num
if j, ok := hashmap[complement]; ok {
return []int{j, i}
}
hashmap[num] = i
}
panic("No two sum solution")
}
四. C++ 实现
暴力法
cpp
std::vector<int> twoSumBruteForce(std::vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); ++i) {
for (int j = i + 1; j < nums.size(); ++j) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
throw std::invalid_argument("No two sum solution");
}
#include
#include
哈希表法
#include <vector>
#include <unordered_map>
#include <stdexcept>
std::vector<int> twoSumHashMap(std::vector<int>& nums, int target) {
std::unordered_map<int, int> hashmap;
for (int i = 0; i < nums.size(); ++i) {
int complement = target - nums[i];
if (hashmap.find(complement) != hashmap.end()) {
return {hashmap[complement], i};
}
hashmap[nums[i]] = i;
}
throw std::invalid_argument("No two sum solution");
}
结论
使用哈希表的解法相比暴力解法有更高的效率,适用于更大的输入数据。暴力解法虽然简单直接,但在大数据集下表现不佳。上述实现覆盖了 Java, Python 和 Golang 三种语言,希望对你有所帮助。