问题:两数之和
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。
求解:
(1)C++代码
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> result;
unordered_map<int,int>mp;
for (int i=0;i<nums.size();i++) {
if (mp.find(target-nums[i])!=mp.end()) {
result={i,mp[target - nums[i]]};
return result;}
mp[nums[i]]=i;
}
return result;}};
int main()
{
Solution solution;
vector<int> nums = {2,7,9,11,23,45,1,5,10,8};
int target = 19;
vector<int> result = solution.twoSum(nums, target);
if (!result.empty())
{cout << "Indices: " << result[0] << ", " << result[1] << endl;}
else
{cout << "No two sum solution." << endl;}
return 0;}
(2)Java代码:
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[0] = i;
result[1] = map.get(target - nums[i]);
return result;
}
map.put(nums[i], i);
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {2, 7, 9, 11, 23, 45, 1, 5, 10, 8};
int target = 19;
int[] result = solution.twoSum(nums, target);
if (result[0] != 0 || result[1] != 0) {
System.out.println("Indices: " + result[0] + ", " + result[1]);
} else {
System.out.println("No two sum solution.");
}
}
}
相比于暴力解法,以空间换时间
时间复杂度O(n);空间复杂度O(n)