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 ...
随机推荐
- unity3d常用属性汇总
unity常用的是C#语言.而C#语言有Attribute属性.特别强大.所以unity开发的时候.可以在变量加Attribute属性来达到开发人员想要的效果 RequireComponent:约束组 ...
- Java文件编码自动转换工具类(只改变编码,不会改变文件内容)
本篇随笔主要介绍了一个用java语言写的将一个文件编码转换为另一个编码并不改变文件内容的工具类: 通过读取源文件内容,用URLEncoding重新编码解码的方式实现. public class Cha ...
- Android笔记——Android中数据的存储方式(二)
我们在实际开发中,有的时候需要储存或者备份比较复杂的数据.这些数据的特点是,内容多.结构大,比如短信备份等.我们知道SharedPreferences和Files(文本文件)储存这种数据会非常的没有效 ...
- JavaScript indexOf() 方法和 lastIndexOf() 方法
一,定义和用法 indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置. lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索 ...
- Windows Azure 上传 VM
One of the great features of Windows Azure is VHD mobility. Simply put it means you can upload and d ...
- SharePoint 2013 中代码创建列表查阅项字段
1.首先,打开VS创建两个List Definition,分别是Address和City,如下图: 2.City列表里修改Title为City Name,其实内部名称还是Title,注意一下: 3.给 ...
- ExtJs中xtype与组件类的对应表
from:http://blog.163.com/jx_dream/blog/static/117056627201223091021410/ 核心提示:我们在使用 ExtJs 创建组件时最容易理解的 ...
- android view holder 优化
android 一般都用viewholder来优化contentView,采用sparseArray能够进一步优化 /** * 用法: ImageView bananaView = ViewHolde ...
- UWP开发-HTTP详解
HTTP作为一个基础功能,有必要介绍下在UWP下的使用方法. 一.Get请求: 一般我们用到的是GetAsync方法 public static async Task Gets(Uri uri) { ...
- iOS设计模式之观察者模式
观察者模式 基本理解 观察者模式又叫做发布-订阅(Publish/Subscribe)模式. 观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象.这个主题对象在状态发生变化时 ...