“给定一个整数数组
nums和一个整数目标值target,请你在该数组中找出 和为目标值target的那 两个 整数,并返回它们的数组下标。“你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
暴力枚举
复杂度
- 时间复杂度
- 空间复杂度
class Solution
{
public:
vector<int> twoSum(vector<int> &nums, int target)
{
int n = nums.size();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (nums[i] + nums[j] == target)
return {i, j};
}
}
return {};
}
};
class Solution {
public int[] twoSum(int[] nums, int target)
{
int n = nums.length;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (nums[i] + nums[j] == target)
return new int[]{i, j};
}
}
return new int[0];
}
}
func twoSum(nums []int, target int) []int {
for i, x := range nums {
for j := i + 1; j < len(nums); j++ {
if x + nums[j] == target {
return []int{i, j}
}
}
}
return nil
}
class Solution:
def twoSum(self, nums: List[int], target:int)
n = len(nums)
for i in range(n):
for j in range(i+1, n):
if nums[i] + nums[j] == target:
return [i, j]
return []
Hash Map
- 时间复杂度
- 空间复杂度
使用哈希表存储nums和索引
具体步骤如下:
- 创建一个空的哈希表
hashtable,用于存储数组中的元素及其对应的索引。- 遍历数组
nums。- 在每次迭代中,计算目标值与当前数组元素的差值
target - nums[i]。- 检查哈希表中是否存在这个差值,如果存在,则表示找到了两个数的和等于目标值
target,返回它们的索引。- 如果不存在,则将当前数组元素
nums[i]作为键,当前索引i作为值存入哈希表,以备后续查找使用。- 若遍历完成后仍未找到符合条件的数对,则返回一个空数组
{}。
class Solution
{
public:
vector<int> twoSum(vector<int> &nums, int target)
{
unorderd_map<int, int> hashmap;
for (int i = 0; i < nums.size(); i++) {
auto it = hashmap.find(target - nums[i]);
if (it != hashmap.end())
return {it -> second, i};
hashmap[nums[i]] = i;
}
return {};
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer,Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}
func twoSum(nums []int, target int) []int {
hashMap := map[int]int{}
for i, x := range nums {
if key, ok := hashMap[target - x]; ok {
return []int{key, i}
}
hashMap[x] = i;
}
return nil
}
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashMap = dict()
for i, num in enumerate(nums):
if target - num in hashMap:
return [hashMap[target - num], i]
hashMap[nums[i]] = i
return []
by KingYen.