leetcode第一题--two sum
Problem:Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
由于水平问题,本题参考了Suool大神的思路。因为我首先想到的居然是两个for,第一个for全部,第二个for从前一个for的迭代加1开始寻找相等记录下标。
class resolution{
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int>::iterator iter, res;
vector<int> result();
res = result.begin();
for (iter = numbers.begin();iter != numbers.end();++iter)
{
for (vector<int>::iterator iter2 = iter + ;iter2!=numbers.end();++iter2)
{
if(*iter + *iter2 == target)
{
*res = iter - numbers.begin() + ;
*(++res) = iter2 - numbers.begin() + ;
return result;
}
}
}
}
};
可想而知运行超时,于是,冷静参考了Suool后,想了下这是最low的N方复杂度。既然超时,那应该是nlogn能解决的。想到排序吧就nlogn了。那就排序吧。用std::sort。
排序之后那就用头尾之和来判断,不断往里缩进直至找到答案为止。
头尾之和小于target的话,那就头要往前才能增大。
头尾之和大于target的话,那就尾要回缩才能缩小。
因为答案有且仅有一个,所以,不断缩进肯定可以找到答案。
找到到答案后,那就根据key值在原来的vector中找,大不了遍历2n就找到下标,push_back到result中就好了。
class Solution{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> result;
vector<int> temp = numbers;
std::sort(temp.begin(),temp.end());
int left = ;
int right = temp.size() - ;
int sum = ;
int index = ;
while(left < right)
{
sum = temp[left] + temp[right];
if (sum == target)
{
while(true)
{
if(numbers[index] == temp[left])
{
result.push_back(index + );
}
// must be 'else if' or the same index will be push_back when the target is composed by two same numbers
else if(numbers[index] == temp[right])
{
result.push_back(index + );
}
if(result.size() == )
{
return result;
}
index++;
}
}
else if (sum < target)
{
left++;
}
else
{
right--;
}
}
}
};
这样就行了。注意当中的else if 避免相同的值相加为target的case导致错误记录index。可以吧else if 改成 if 提交看下错误提示就知道了。
有位更叼的大神居然用n就解决了http://www.tuicool.com/articles/RBNjuu
2015/01/08:
今天有个人问我这题,然后说了以上方法,顺带写了个hash的O(n)
class Solution{
public:
vector<int> twoSum(vector<int> &numbers, int target){
vector<int> result;
unordered_map<int, int> umap;
for (int i = ; i < numbers.size(); i++){
umap[numbers[i]] = i + ;
}
for (int i = ; i < numbers.size(); i++){
int umapVal = umap[target - numbers[i]];
if (umapVal && umapVal != i + ){
result.push_back(i + );
result.push_back(umap[target - numbers[i]]);
break;
}
}
return result;
}
};
就是用hash记录每个值的下标,以便于target减去一个值之后可以O(1)时间找到剩下的知否在当前给定的值里。是的话就返回下标return了。
需要注意的是,你要找的剩下的值是否在给定的里面要加一个不是本身的判断,因为例子target = 6, 给定 3, 2, 4 的时候,umap != i + 1 就派上用场了。
2015/04/03:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
unordered_map<int, int> umap;
vector<int> ans;
for (int i = ; i < numbers.size(); ++i){
umap[numbers[i]] = i + ;
}
for (int i = ; i < numbers.size(); ++i){
if (umap.count(target - numbers[i]) && i + != umap[target - numbers[i]]){
ans.push_back(i + );
ans.push_back(umap[target - numbers[i]]);
}
}
return ans;
}
};
leetcode第一题--two sum的更多相关文章
- LeetCode第一题—— Two Sum(寻找两数,要求和为target)
题目描述: Given an array of integers, return indices of the two numbers such that they add up to a speci ...
- LeetCode算法题-Two Sum II - Input array is sorted
这是悦乐书的第179次更新,第181篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第38题(顺位题号是167).给定已按升序排序的整数数组,找到两个数字,使它们相加到特定 ...
- 乘风破浪:LeetCode真题_040_Combination Sum II
乘风破浪:LeetCode真题_040_Combination Sum II 一.前言 这次和上次的区别是元素不能重复使用了,这也简单,每一次去掉使用过的元素即可. 二.Combination Sum ...
- 乘风破浪:LeetCode真题_039_Combination Sum
乘风破浪:LeetCode真题_039_Combination Sum 一.前言 这一道题又是集合上面的问题,可以重复使用数字,来求得几个数之和等于目标. 二.Combination Sum ...
- LeetCode算法题-Two Sum IV - Input is a BST(Java实现)
这是悦乐书的第280次更新,第296篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第148题(顺位题号是653).给定二进制搜索树和目标数,如果BST中存在两个元素,使得 ...
- LeetCode算法题-Path Sum III(Java实现)
这是悦乐书的第227次更新 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第94题(顺位题号是437).您将获得一个二叉树,其中每个节点都包含一个整数值.找到与给定值相加的路径数 ...
- LeetCode算法题-Range Sum Query Immutable(Java实现)
这是悦乐书的第204次更新,第214篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第70题(顺位题号是303).给定整数数组nums,找到索引i和j(i≤j)之间的元素之 ...
- LeetCode算法题-Path Sum(Java实现)
这是悦乐书的第169次更新,第171篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第28题(顺位题号是112).给定二叉树和整数sum,确定树是否具有根到叶路径,使得沿路 ...
- leetcode第一题(easy)
第一题:题目内容 Given an array of integers, return indices of the two numbers such that they add up to a sp ...
随机推荐
- 【MySQL案件】ERROR 1418
1.1.1. ERROR 1418 [环境的叙述性说明] mysql5.0.67 [问题叙述性说明] 当它来到创建存储过程ERROR 1418一个错误. # 创建函数SQL声明 CREATE FUNC ...
- Android中部署自己的su
本人博客原文 首先把你的自己的su的放到Android应用程序project的assets文件夹,为了和系统的su区分,我自己的su文件叫做sur. 另外我这里没有考虑x86架构的cpu的手机. 废话 ...
- 键盘enter事件时间页面绑定
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 一个sql的优化
原文:一个sql的优化 目的:为了查询某天某个服务器上的登录id的个数 刚开始编写的sql: select count(a.mac) logusers from Log_MacLogin_All ...
- JAVA连接ACCESS、MYSQL、SQLSEVER、ORACLE数据库
. 概要 1.1 JDBC概念 JDBC(Java Database Connectivity)是Java语言为了支持SQL功能而提供的与数据库连接的用户的接口.JDBC中包含了一组由(Java)语言 ...
- HDU 4916 Count on the path
意甲冠军: 考虑到一棵树,m询价 不要求回答每一次询价u和v通过在两个节点形成的最低等级点路径 思路: 一開始以为是LCA- 只是T了好几次- 后来发现不用LCA也可做 考虑每一个询问u和v ...
- springMVC框架建设进程
1.创建Dynamic Web Project 2.导入spring和springmvc所须要的文件 3.配置web.xml文件 3.1 监听spring上下文容器 3.2 载入spring的xml文 ...
- 【关节点+桥】关节点和桥模板 Tarjan
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; con ...
- zoj 3203 Light Bulb,三分之二的基本问题
Light Bulb Time Limit: 1 Second Memory Limit: 32768 KB Compared to wildleopard's wealthiness, h ...
- Rightmost Digit(快速幂)
Description Given a positive integer N, you should output the most right digit of N^N. ...