/*题目:
实现一个函数,该函数接受一个整数数组和一个目标值,并返回数组中和为目标值的两个元素的索引,假设每个输入只有一个解,而且不可以使用同一个元素两次。
问题函数定义:
cpp
vector<int> twoSum(vector<int>& nums, int target);
裁判测试程序样例:
cpp
//1.双指针法left右移,right左移
*/
#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
vector<pair<int, int>> numIndexPairs; // 存储数字和对应索引的 pair
for (int i = 0; i < nums.size(); ++i) {
numIndexPairs.push_back({nums[i], i}); // 将数字和对应索引存入 pair 中
}
sort(numIndexPairs.begin(), numIndexPairs.end()); // 按数字大小排序
int left = 0, right = numIndexPairs.size() - 1;
while (left < right) {
int sum = numIndexPairs[left].first + numIndexPairs[right].first;
if (sum == target) {
result.push_back(numIndexPairs[left].second);
result.push_back(numIndexPairs[right].second);
break;
} else if (sum < target) {
left++;
} else {
right--;
}
}
if (result.empty()) {
result.push_back(-1);
result.push_back(-1);
}
return result;
}
int main() {
vector<int> nums = { 2, 7, 11, 15 };
int target = 9;
vector<int> result = twoSum(nums, target);
cout << "Indices of the two numbers whose sum is " << target << " are: [" << result[0] << ", " << result[1] << "]" << endl;
return 0;
}
/*输入样例:
{ 2, 7, 11, 15 }
9
输出样例:
Indices of the two numbers whose sum is 9 are: [0, 1]
*/
//2.使用unordered_map存储索引和值
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
unordered_map<int, int> map; // 使用unordered_map来存储元素和索引的映射
int n = nums.size();
for (int i = 0; i < n; ++i) {
int complement = target - nums[i];
if (map.count(complement)) {
// 找到和为目标值的两个元素,返回它们的索引
result.push_back(map[complement]);
result.push_back(i);
break;
}
map[nums[i]] = i; // 将元素和索引的映射关系存入unordered_map
}
return result;
}
int main() {
vector<int> nums = {2, 7, 11, 15};
int target = 9;
vector<int> result = twoSum(nums, target);
if (result.size() == 2) {
cout << "Indices of the two numbers whose sum is " << target << " are: [" << result[0] << ", " << result[1] << "]" << endl;
} else {
cout << "No two numbers found whose sum is " << target << endl;
}
return 0;
}