题目链接:leetcode.
嘎嘎,第一题,梦开始的地方;)
O(N^2) O(1)
/*
执行用时:12 ms, 在所有 C++ 提交中击败了25.64%的用户
内存消耗:8.7 MB, 在所有 C++ 提交中击败了43.38%的用户
*/
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
if(nums.empty())
return {};
int N = nums.size();
for(int i = 0;i < N;++i)
{
for(int j = i + 1;j < N;++j)
{
if(nums[i] + nums[j] == target)
{
return {i, j};
}
}
}
return {};
}
};
空间换时间,用哈希表
O(N) O(N)
/*
执行用时:8 ms, 在所有 C++ 提交中击败了55.86%的用户
内存消耗:8.8 MB, 在所有 C++ 提交中击败了26.19%的用户
*/
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
if(nums.empty())
return {};
int N = nums.size();
unordered_map<int, int> M;
for(int i = 0;i < N;++i)
{
//这里不能用M[target - nums[i]],因为下标是从0开始呢
if(M.count(target - nums[i]) != 0)
{
return {M[target - nums[i]], i};
}
M[nums[i]] = i;
}
return {};
}
};
2万+

被折叠的 条评论
为什么被折叠?



