標籤:leetcode twosum
原題:
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=9Output: index1=1, index2=2
翻譯:
給定一個整型數組,找出能相加起來等於一個特定目標數位兩個數。函數twoSum返回這兩個相加起來等於目標值的數位索引,且index1必須小於index2。請記住你返回的答案(包括index1和index2)都不是從0開始的。你可以假定每個輸入都有且僅有一個解決方案。Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2
C++
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int> mapping; vector<int> 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<Integer,Integer> map=new HashMap<Integer,Integer>(); int[] result=new int[2]; for(int i=0;i<nums.length;i++){ map.put(nums[i], i); } for(int i=0;i<nums.length;i++){ int searched=target-nums[i]; if(map.containsKey(searched)&&map.get(searched)!=i){ int index=map.get(searched); if(index<i){ result[0]=map.get(searched)+1; result[1]=i+1; }else{ result[0]=i+1; result[1]=map.get(searched)+1; } } } return result; }}
著作權聲明:本文為 NoMasp柯於旺 原創文章,未經許可嚴禁轉載!歡迎訪問我的部落格:http://blog.csdn.net/nomasp
LeetCode 1 Two Sum