原題:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target,
where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
翻譯:
給定一個整型數組,找出能相加起來等於一個特定目標數字的兩個數。
函數twoSum返回這兩個相加起來等於目標值的數字的索引,且index1必須小於index2。
請記住你返回的答案(包括index1和index2)都不是從0開始的。
你可以假定每個輸入都有且僅有一個解決方案。
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
C++
class Solution {
public:
vector twoSum(vector& nums, int target) {
map mapping;
vector result;
for (int i = 0; i < nums.size(); i++)
{
mapping[nums[i]] = i;
}
for (int i = 0; i < nums.size(); i++)
{
int searched = target - nums[i];
if (mapping.find(searched) != mapping.end()
&& mapping.at(searched) != i)
{
result.push_back(i + 1);
result.push_back(mapping[searched] + 1);
break;
}
}
return result;
}
};
Java
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap map=new HashMap();
int[] result=new int[2];
for(int i=0;i
版權聲明:本文為 NoMasp柯於旺 原創文章,未經許可嚴禁轉載!歡迎訪問我的博客:http://blog.csdn.net/nomasp