LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告
偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积累可以对以后在对算法中优化带来好处。Ok,今天是我做的第一题Add Two Sum。
题目要求
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
题目分析
第一次刷LeetCode,太大意了,以为第一题很简单,两层循环,结果 time limit out 超时了。然后看了一眼show tag 尼玛,上档了,果然得用哈希的方法来做。
思路:
根据题目的要求给定一个数组,从中选出两个数,使得两个数的和等于target目标值。
解法如下:
1. 首先将数组的数插入到map中,同时map的key为数组的值,而value等于数组的下标
2. 从map开始遍历,从target减去当前的iter->first 即value1,这里first是键也是原来numbers数组中的值
3. 得到另一个值value2,查看map中是否存在该键,若存在看value1+value2是否等于target
4. 若等于target判断,是否为target的二分之一,因为会出现相同的值,若target为一个value值的两倍,从数组充查找是否存在有两个value,若存在则加入reslut
5. 若不是,则从map中直接取出键所对应的值,按小的在前的顺序放入result,因为map中“值”存放的是实际数组的下标,“键”存放的是实际数组中的值。最后输出result即可。
示例代码
#include<iostream>
#include<vector>
#include<map>
#include<math.h>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
map<int,int> nummap;
map<int,int>::iterator i;
for(int i = 0 ;i < numbers.size(); i++)
nummap.insert(make_pair(numbers[i],i+1));//map中key存放numbers数组的值,value存放下标
for(map<int ,int >::iterator iter = nummap.begin(); iter!= nummap.end(); iter++)
{
int value1 = iter->first;
int value2 = target - value1;
i = nummap.find(value2);
if( i != nummap.end())
{
if(value1 + value2 == target)
{
if(value1 == value2)//看找到的值是否为target的二分之一,若是二分之一,必须存在2个才符合要求
{
vector<int>::iterator j;
vector<int>::iterator k = find (numbers.begin(), numbers.end(), value1);
if(k!= numbers.end())//看是否存在两个
{
j = find(k+1, numbers.end(), value1);
if(j!= numbers.end())
{
result.push_back(k-numbers.begin()+1);
result.push_back(j-numbers.begin()+1);
return result;
}
}
}
else//若不是二分之一,说明存在两个不同下标的不同值相加为target,从map中取出他们相应的索引
{
result.push_back(min(nummap[value1],nummap[value2]));
result.push_back(max(nummap[value1],nummap[value2]));
return result;
}
}
}
}
return result;
}
};
int main ()
{
Solution s1;
int num[] ={0, 2, 4, 0};
vector<int> numbers (num,num+4);
int target = 0;
vector<int> result = s1.twoSum(numbers, target);
for(int i = 0 ;i < result.size(); i++)
{
cout<< result[i]<<endl;
}
return 0;
}
LeetCode 1 Two Sum 解题报告的更多相关文章
- LeetCode: Minimum Path Sum 解题报告
Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to b ...
- LeetCode 2 Add Two Sum 解题报告
LeetCode 2 Add Two Sum 解题报告 LeetCode第二题 Add Two Sum 首先我们看题目要求: You are given two linked lists repres ...
- 【LeetCode】120. Triangle 解题报告(Python)
[LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...
- 【LeetCode】Permutations II 解题报告
[题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...
- 【LeetCode】Island Perimeter 解题报告
[LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...
- 【LeetCode】01 Matrix 解题报告
[LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...
- 【LeetCode】Largest Number 解题报告
[LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...
- 【LeetCode】Gas Station 解题报告
[LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...
- LeetCode: Combination Sum 解题报告
Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...
随机推荐
- C# Web Forms - Using jQuery FullCalendar
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> ...
- string.join加引号
columnsGen = string.Join(",", modelDictionary.Keys); valueGen = modelDictionary.Values.Agg ...
- js 当前日期及时间
返回时间格式 : 2016-07-22 10:22:30 function getNowFormatDate() { var date = new Date(); var seperator1 = & ...
- 不变(Invariant), 协变(Covarinat), 逆变(Contravariant) : 一个程序猿进化的故事
阿袁工作的第1天: 不变(Invariant), 协变(Covarinat), 逆变(Contravariant)的初次约 阿袁,早!开始工作吧. 阿袁在笔记上写下今天工作清单: 实现一个scala类 ...
- linux压缩和解压命令总结
一.tar.gz tar -xzvf 二.tar.bz2 tar.bz2 解压命令 bzip2 -d gcc-4.1.0.tar.bz2---上面解压完之后执行下面的命令.执行成功后,会解压生成一个 ...
- 【GOF23设计模式】状态模式
来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_状态模式.UML状态图.酒店系统房间状态.线程对象状态切换 package com.test.state; public ...
- 当Thread.Sleep的暂停时间参数设置过小时,精度很差的解决方法
一.问题产生 在C#和C++中有这样一个函数:void Sleep(int Timeout),可以让线程暂停指定的毫秒数. 但是我在win8下调用这个函数实现按照固定频率发送udp数据包时,会有一个问 ...
- COMMIT WORK AND WAIT 是在WAIT什么
wait 还是不wait,这是个问题. 这是同步更新还是异步更新的问题:如果是只commit work,是异步更新,触发注册在当前SAP LUW中所有数据更新动作,数据更新动作由SAP的更 ...
- 应用程序代理AppDelegate解析
应用程序UIApplication是通过代理和外部交互的,当应用程序生命周期中发生改变时UIApplication就会调用代理对应的方法. @implementation AppDelegate - ...
- C语言泛型编程--抽象数据类型
一.数据类型: 在任何编程语言中,数据类型作为一个整体,ANSI-C包含的类型为:int.double.char……,程序员很少满意语言本身提供的数据类型,一个简单的办法就是构造类似:array.st ...