您的位置:首页 > 其它

Leetcode[1] Two Sum

2015-04-28 17:17 295 查看
Givenan array of integers, find two numbers such that they add up to a specifictarget number

Thefunction twoSum should return indices of the two numbers such that they addup to the target, where
index1must be less than index2. Please note that your returned answers (bothindex1 and index2)
are notzero-based.

Youmay assume that
each inputwould have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

思路:构建一个hashtable,将2,7,11,15被9减去的值,作为key进行保存(value存index1的索引值),然后遍历一遍数组看有没有一个key就可以.

考点:Map,Vector

JAVA版:

第一版 446MS bug free

public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap();
for(int i = 0; i < nums.length; i++){
int key = target - nums[i];
map.put(key, i+1);
}
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
int index = i+1;
if(index == map.get(nums[i]))
continue;
return new int[]{index<map.get(nums[i])?index:map.get(nums[i]), index>map.get(nums[i])?index:map.get(nums[i])};
}
}
return null;
}
}


第二版 369MS

public class Solution {
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
int x = numbers[i];
if (map.containsKey(target - x)) {
return new int[] { map.get(target - x) + 1, i + 1 };
}
map.put(x, i);
}
return null;
}
}


C++版本:

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
map<int,int> compareMap;
map<int,int> compareMap2;
vector<int>::iterator iter=numbers.begin();
vector<int> result;
int count = 1;
int length = numbers.size();
for(int i = 0; i < length; ++i)
<span style="white-space:pre">	</span>compareMap[numbers[i]] = i;

vector<int>::iterator iter2=numbers.begin();
int index1 = 1;
map<int,int>::iterator it = compareMap.end();  ///////
while (iter2 != numbers.end()){

it = compareMap.find(target - *iter2);
if (it != compareMap.end()){
int index2 = it->second+1;
if (index1==index2){
iter2++;
index1++;
continue;
}
result.push_back(index1);
result.push_back(index2);
break;
}
index1++;
iter2++;
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: