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语言范例学习01
编程语言的能力追求T型. 以前学过C语言,但是只学了理论. 从今天开始,我买了本<C语言程序开发范例宝典>.我要把它通关掉. 这应该可以极大地提升我的编程能力. 第一章 基础知识 这章没太 ...
- cas与NGINX整合(转)
CAS (5) -- Nginx代理模式下浏览器访问CAS服务器配置详解 标签: 服务器 2015-12-18 15:04 1633人阅读 评论(0) 收藏 举报 分类: 网络(61) 目录( ...
- SQL SERVER获取数据库文件信息
MS SQL SERVER 获取当前数据库文件等信息,适用于多个版本: SELECT dbf.file_id AS FileID , dbf.name AS [FileName] , s.fi ...
- [C#]多线程下载
发现电脑里以前编写的下载程序... 做个记录,那时做的挺匆忙的,没用委托,通过公开出窗体来修改下载进度,做的比较乱... ==!! 程序具体功能(流程): 1.检测系统托盘图标内的进程名是否符合要求 ...
- 高性能JS笔记1——加载执行
一.脚本位置 1.Script标签尽可能放到Body底部,以减少脚本文件下载对整个页面UI渲染的影响. 2.Script标签永远不要紧跟Link标签后面. 二.组织脚本 1.合并多个文件在一个Scri ...
- 安卓开发_浅谈Android动画(四)
Property动画 概念:属性动画,即通过改变对象属性的动画. 特点:属性动画真正改变了一个UI控件,包括其事件触发焦点的位置 一.重要的动画类及属性值: 1. ValueAnimator 基本属 ...
- CAS实现单点登入(sso)经典教程
本教程我已按照步骤实现,不过要深入了解单点登入还需要进一步的学习,掌握其中的精髓. 一.简介 1.cas是有耶鲁大学研发的单点登录服务器 2.本教材所用环境 Tomcat7.2 JDK6 CAS Se ...
- UVa 112 - Tree Summing(树的各路径求和,递归)
题目来源:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&pa ...
- Java Concurrency In Practice -Chapter 2 Thread Safety
Writing thread-safe code is managing access to state and in particular to shared, mutable state. Obj ...
- nginx设置反向代理后,页面上的js css文件无法加载
问题现象: nginx配置反向代理后,网页可以正常访问,但是页面上的js css文件无法加载,页面样式乱了. (1)nginx配置如下: (2)域名访问:js css文件无法加载: (3)IP访问:j ...