上完C++的课就在也没用过C++了,最近要找实习,发现自己没有一门语言称得上是熟练,所以就重新开始学C++。记录自己从入门到放弃的过程,论C++如何逼死花季少女。

题目: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.

大意就是,给一个vector和target,在vector中找到两个数加起来等于target。

没仔细想就提交了自己的暴力解法。运行时间238ms,果真菜的不行,这个题最好的成绩是3ms。

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for(int i = 0; i != nums.size(); i++)
for(int j = i + 1; j!= nums.size(); j++)
if (nums[i] + nums[j] == target){
result.push_back(i);
result.push_back(j);
return result;
}
}
};

  

果断换一种解法,双指针法:将数组排序,用两个指针,i指向数组首元素,j指向数组尾元素,两个元素相加,大于target就j--,小于target就i--,找到正确的i、j之后,还要确定其在原数组中的下标,查找时要避免两个元素值相同时返回的下标也相同。例如:Input:[3,3]  6 ;Output:[0,0]  ; Expected:[0,1],提交之后运行时间为8ms

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
vector<int> sortednums(nums);
sort(sortednums.begin(),sortednums.end());
int i = 0, j = sortednums.size()-1;
while(i != j){
if (sortednums[i] + sortednums[j] > target)
j--;
else if (sortednums[i] + sortednums[j] < target)
i++;
else
{
vector<int>::iterator it =find(nums.begin(),nums.end(),sortednums[i]);
i = distance(nums.begin(),it);
nums[i] = nums[i] +1;
it = find(nums.begin(),nums.end(),sortednums[j]);
result.push_back(i);
result.push_back(distance(nums.begin(),it));
return result;
}
}
}
};
第三种方法:用map查找,在把数组中元素向map中插入时,先判断target-nums[i]在不在map中,这样可以避免数组中的重复元素进map。提交之后10ms,比方法2慢,之后再分析复杂度吧。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
map<int,int> hashtable;
map<int,int>::iterator it;
for(int i = 0; i!= nums.size(); i++)
{
it = hashtable.find(target - nums[i]);
if (it != hashtable.end())
{
result.push_back(it->second);
result.push_back(i);
return result;
}
else if (!hashtable.count(nums[i]))
hashtable.insert(make_pair(nums[i], i));
}
}
};

  

大神的代码,3ms,先贴着,之后再分析。
static const auto __________ = []()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}(); class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
using SizeType = remove_reference_t<decltype(nums)>::size_type;
using ValueToIndexMapType = unordered_map<int, SizeType>;
ValueToIndexMapType map;
vector<int> indices(2);
for (SizeType index = 0; index < nums.size(); ++index)
{
const auto foundIterator = map.find(target - nums[index]);
if (foundIterator != end(map) && foundIterator->second != index)
return vector<int>{ index, foundIterator->second };
else
map.emplace(nums[index], index);
}
throw std::runtime_error("Solution not found");
}
};

  

哎!又菜又懒,没救了。

C++ leetcode::two sum的更多相关文章

  1. LeetCode:Path Sum I II

    LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...

  2. 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)

    剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...

  3. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  4. [LeetCode] Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

  5. [LeetCode] Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  6. [LeetCode] Range Sum Query 2D - Mutable 二维区域和检索 - 可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  7. [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  8. [LeetCode] Range Sum Query 2D - Immutable 二维区域和检索 - 不可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  9. [LeetCode] Range Sum Query - Immutable 区域和检索 - 不可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  10. [LeetCode] Combination Sum III 组合之和之三

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

随机推荐

  1. vue--vuex

    https://vuex.vuejs.org/ vuex是专为 vue.js 应用程序开发的 状态管理模式 采用集中式存储管理应用的所有组件状态 并以相应的规则保证状态以一种可预测的方式发生变化 vu ...

  2. python 安装包

    一般python的包都是.tar.gz结尾的压缩包,据说是linux下面的格式.但也是可以在windows上面安装的,安装过程,1,在 https://pypi.python.org/pypi 这个网 ...

  3. 你真的了解restful api吗?

    前言 在以前,一个网站的完成总是“all in one”,页面,数据,渲染全部在服务端完成,这样做的最大的弊端是后期维护,扩展极其痛苦,开发人员必须同时具备前后端知识.于是慢慢的后来兴起了前后端分离的 ...

  4. 学习笔记58—3D杯子设计

    软件下载:http://www.i3done.com/ 界面如下: 3D杯子设计步骤(参考:http://www.i3done.com/news/video/402.html): 生成杯体 1.点击基 ...

  5. Visual Studio 2015+InstallShield 2015

    下载Installshield http://learn.flexerasoftware.com/content/IS-EVAL-InstallShield-Limited-Edition-Visua ...

  6. 大数据 - spark-sql 常用命令

    --spark启动 spark-sql --退出 spark-sql> quit; --退出spark-sql or spark-sql> exit; 1.查看已有的database sh ...

  7. Program Option Modifiers

    Some option are 'boolean' and control behavior that can be turned on or off. --column-names option d ...

  8. TStringList 常用方法与属性

    /TStringList 常用方法与属性 :varList: TStringList;i: Integer;begin List := TStringList.Create;List.Add('Str ...

  9. 雷林鹏分享:XML 简介

    XML 简介 XML 被设计用来传输和存储数据. HTML 被设计用来显示数据. 应该掌握的基础知识 在您继续学习之前,需要对以下知识有基本的了解: HTML JavaScript 如果您希望首先学习 ...

  10. 中心极限定理 | central limit theorem | 大数定律 | law of large numbers

    每个大学教材上都会提到这个定理,枯燥地给出了定义和公式,并没有解释来龙去脉,导致大多数人望而生畏,并没有理解它的美. <女士品茶>有感 待续~ 参考:怎样理解和区分中心极限定理与大数定律?