始于
分类:LeetCode
Tags: [ LeetCode ]
LeetCode 百题计划 - 1. Two Sum - 始まりの旅
LeetCode 1. Two Sum
1. Two Sum
Difficulty: easy Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
1st Version:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); ++i) {
for (int j = i + 1; j < nums.size(); ++j) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {};
}
};
Rate:
Runtime: 132 ms, faster than 36.06% of C++ online submissions for Two Sum.
Memory Usage: 9.1 MB, less than 98.86% of C++ online submissions for Two Sum.
作为LeetCode上一个标记为easy的题目, 如期所愿, 按照老实人方法进行暴力并没有超时, 但是实际上并没有在时间上击败太多的人.
参考讨论区和叔的gitpage页, 接下来尝试使用哈希表来解.
但是老实人表示, hashtable只有pb_ds库里有呀. 别担心, 不可重复的map和set内部是由红黑树实现的, 而可重set和map内部是由哈希表实现的, 别忘了.
2nd Version:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
// key: num, value: pos
unordered_map<int, int> ump;
for (int i = 0; i < nums.size(); ++i) {
ump[nums[i]] = i;
}
for (int i = 0; i < nums.size(); ++i) {
auto another = target - nums[i];
if (ump.find(another) != end(ump) && ump[another] != i) {
return {i, ump[another]};
}
}
return {};
}
};
Rate:
Runtime: 8 ms, faster than 93.74% of C++ online submissions for Two Sum.
Memory Usage: 10.4 MB, less than 15.24% of C++ online submissions for Two Sum.
速度提升了不少, 但是理所当然的, 这是一种拿空间换时间的手段. 但是在多数情况下, 时间是比空间更宝贵的东西, 无论是竞赛, 还是现实中.
再看讨论区, 发现了一种利用hashtable边添加边搜索的方法, 这种其实类似我的第一个版本解法 – 不搜当前元素之前的元素; 而这种做法, 是不搜当前元素之后的元素:
3rd Version:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> ump;
for (int i = 0; i < nums.size(); ++i) {
auto another = target - nums[i];
auto itr = ump.find(another);
if (end(ump) != itr) {
return {i, itr->second};
} else {
ump.emplace(nums[i], i); // since C++11
// or ump.insert(make_pair(nums[i], i));
}
}
return {};
}
};
Rate:
Runtime: 4 ms, faster than 99.76% of C++ online submissions for Two Sum.
Memory Usage: 10.1 MB, less than 43.32% of C++ online submissions for Two Sum.