给定一个数组 nums 和一个目标值 target,在该数组中找出和为目标值的两个数
时间: 2023-10-29 13:35:04 浏览: 52
示例:
输入: nums = [2, 7, 11, 15], target = 9
输出: [0, 1]
解释: nums[0] + nums[1] = 2 + 7 = 9,因此返回 [0, 1]。
思路:
可以使用哈希表来解决此问题。遍历数组中的每个元素,在哈希表中查找是否存在与当前元素相加等于 target 的另一个元素。如果存在则返回这两个元素的下标,否则将当前元素加入哈希表中,以便后续查找。
代码实现:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (hash.count(complement)) {
return {hash[complement], i};
}
hash[nums[i]] = i;
}
return {};
}
};
相关问题
给定整数数组nums和一个目标值target 在数组中找出和为目标值的两个整数 返回数组下标
题目描述:
给定一个整数数组 nums 和一个目标值 target,请在数组中找出和为目标值的两个整数,返回它们的数组下标。
示例:
输入:nums = [2, 7, 11, 15], target = 9
输出:[0, 1]
解释:nums[0] + nums[1] = 2 + 7 = 9,因此返回 [0, 1]。
思路:
暴力枚举法:对于每一个数,遍历整个数组,查找另一个数是否与它的和为目标值。
哈希表法:遍历数组,将每个数及其下标存储在哈希表中,同时查找哈希表中是否存在目标值减去当前数的差值。
代码实现:
暴力枚举法:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
res.push_back(i);
res.push_back(j);
return res;
}
}
}
return res;
}
};
哈希表法:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int, int> map;
for (int i = 0; i < nums.size(); i++) {
if (map.find(target - nums[i]) != map.end()) {
res.push_back(map[target - nums[i]]);
res.push_back(i);
return res;
}
map[nums[i]] = i;
}
return res;
}
};
给定整数数组nums和一个目标值target 在数组中找出和为目标值的两个整数 返回数组下标java
思路:使用哈希表存储已经遍历过的数字,遍历数组nums,对于每个数字num,查找是否存在另一个数字target-num在哈希表中,如果存在,返回两个数字的下标。
Java代码实现:
class Solution {
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");
}
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)