C++ leetcode::two sum
上完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;
}
}
}
};
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));
}
}
};
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的更多相关文章
- 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 ...
- 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)
剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...
- [LeetCode] Path Sum III 二叉树的路径和之三
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] Combination Sum IV 组合之和之四
Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...
- [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 ...
- [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 ...
- [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- [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 ...
- [LeetCode] Range Sum Query - Immutable 区域和检索 - 不可变
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- [LeetCode] Combination Sum III 组合之和之三
Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...
随机推荐
- 屏幕尺寸,分辨率,像素,PPI之间到底什么关系?
转载自:http://www.jianshu.com/p/c3387bcc4f6e 感谢博主的无私分享. 今天我给大家来讲讲这几个咱们经常打交道的词到底啥意思,以及他们之间到底有什么关系.这篇文章是我 ...
- Qt532.数值转为16进制(并填充)
ZC:QString::number(要转换的数值, 需要转换的目标进制); ZC:QString("%1").arg(要转换的数值, 需要填充到?位, 需要转换的目标进制, 用于 ...
- 首篇 sdk 之 AlertDialog
带着十足的干劲,用着有限的英语水平,我们来看看sdk里docs里的AlertDialog: AlertDialog SDK 原文描述:A dialog that can show a title, u ...
- Javascript 常用设计模式
转载自:https://blog.csdn.net/buptlyz/article/details/52018193 单例模式(模块模式):确保始终只创建一个实例的对象时使用的设计模式. 为什么需要采 ...
- Cordova+Vue快速搭建Hybrid App
前言 最近项目迭代需要开发一个app,由于项目组其他系统前端技术栈都是Vue,所以自己在需求评估的时候就初步敲定了Cordova+Vue的前端架构,后来查阅了不少资料,也掉了不少坑,这里总结一下,也算 ...
- SpringBoot 文件上传、下载、设置大小
本文使用SpringBoot的版本为2.0.3.RELEASE 1.上传单个文件 ①html对应的提交表单 <form action="uploadFile" method= ...
- (转)linux各文件夹的作用
原文地址:<linux各文件夹的作用> linux下的文件结构,看看每个文件夹都是干吗用的/bin 二进制可执行命令 /dev 设备特殊文件 /etc 系统管理和配置文件 /etc/rc. ...
- AtCoder Beginner Contest 110 D - Factorization
D - Factorization 思路:把相同的质因子看成相同的小球,求把这些小球放进n个盒子里的方案数. 代码: #pragma GCC optimize(2) #pragma GCC optim ...
- 浏览器缓存之Expires Etag Last-Modified max-age详解
前段时间去面试移动端的H5开发工程师,在最后面试的时候被问到了max-age Expires Etag有什么不同,在什么情况下应用,当时乱编了一通,自我感觉良好,结果…… 大家懂得,现在讲他们几个的区 ...
- 验证码之SimpleCaptcha (二)
上回说到了简单的使用simpleCaptcha,这次我们这次我们将讲解扩张simpleCaptcha. 回到正题,我们需要一些自定义的验证码,比如验证码的字体大小,背景,颜色等等,默认的验 ...