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 解题报告的更多相关文章

  1. 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 ...

  2. LeetCode 2 Add Two Sum 解题报告

    LeetCode 2 Add Two Sum 解题报告 LeetCode第二题 Add Two Sum 首先我们看题目要求: You are given two linked lists repres ...

  3. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  4. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  5. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  6. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

  7. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  8. 【LeetCode】Gas Station 解题报告

    [LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...

  9. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

随机推荐

  1. java之Class类详解

    测试中需要用到的代码 InterfaceA代码: package jichu; interface InterfaceA { String s1 = "this is s1 in Inter ...

  2. File文件的Api的各种方法

    package com.immoc; import java.io.File; import java.io.IOException; public class Fileto { public sta ...

  3. question about import google file

    1. question descibe; once, one css file(app.css) of my web project has sentence like this: @import u ...

  4. Linux命令详解之–ls命令

    今天开始为大家介绍下Linux中常用的命令,首先给大家介绍下Linux中使用频率最高的命令--ls命令. 更多Linux命令详情请看:Linux命令速查手册 linux ls命令用于显示指定工作目录下 ...

  5. lazyload.js详解

    简介 lazyload.js用于长页面图片的延迟加载,视口外的图片会在窗口滚动到它的位置时再进行加载,这是与预加载相反的. 优点: 它可以提高页面加载速度: 在某些情况清晰它也可以帮助减少服务器负载. ...

  6. Sharepoint学习笔记—习题系列--70-573习题解析 -(Q28-Q31)

    Question28You have a Microsoft Office SharePoint Server 2007 site.You upgrade the site to SharePoint ...

  7. iOS沙盒简单介绍

    先简单介绍一下什么是沙盒:你可以简单理解成为一个目录,这个目录的改动不会对操作系统造成任何损失.(这里也有一点点介绍) 看看苹果的沙盒目录: 再附一张苹果官方的图 一个iOS app操作都是在自己的沙 ...

  8. NSOperation创建队列

    #pragma mark - NSOperation //NSOperation不能直接进行多线程的创建,需要帮助:NSOperationQueue // 使用NSOperation的第一个子类去创建 ...

  9. 全球最低功耗蓝牙单芯片DA14580的软件体系 -层次架构和BLE消息事件处理过程

    在作者之前发表的<全球最低功耗蓝牙单芯片DA14580的系统架构和应用开发框架分析>.<全球最低功耗蓝牙单芯片DA14580的硬件架构和低功耗>.<全球最低功耗蓝牙单芯片 ...

  10. 关于报malformed or corrupted AST file: 'Unable to load module 的错~

    今天早上 一运行程序 居然报错,我都惊呆了,昨天明明好好的-但是百度是强大的- 报错内容: malformed or corrupted AST file: 'Unable to load modul ...