Two Sum

Total Accepted: 125096 Total Submissions: 705262

Question Solution

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

在一个数组中,找出两个数字的和等于target的下标。

Java直接暴露找,提交还通过过了,时间复杂度:O(N^2)

public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
for(int i=0;i<nums.length-1;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j] == target){
res[0] = i+1;
res[1] = j+1;
}
}
}
return res;
}
}

下面是根据hashmap,在把数组中的数存在Map之间,先要把target减去数组中的这个数字,对后来进入的数组,判断这个数是否在map中,如果在,说明找到了这两个数

这样的时间复杂度是O(N)

public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int[] res = new int[2];
for(int i=0;i<nums.length;i++){
if(map.containsKey(nums[i])){
int index = map.get(nums[i]);
res[0] = index + 1;
res[1] = i + 1;
}else{
map.put(target - nums[i],i);
}
}
return res;
}
}

下面用Python以此实现上面的两个程序

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
res=[0,0]
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i] + nums[j] == target:
res[0]= i+1
res[1]= j+1
return res

很荣幸,这个提示时间超时

根据字典dict

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dicts = {}
for i in range(len(nums)):
if nums[i] in dicts.keys():
return (dicts[nums[i]],i+1)
else:
dicts[target- nums[i]] = i + 1

字典的key = nums[i],value=i+1

这里每次是吧target-nums[i] i+1 分布以key 和value 存入字典的,对后面的nums[i] 判断是否在字典中,在的话,说明结束程序

当然也可以每次吧nums[i] i+1 存在字典中,判断target-nums[i] 是否已经在字典中了

如下程序,一样AC

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dicts = {}
for i in range(len(nums)):
if target - nums[i] in dicts.keys():
return (dicts[target - nums[i]],i+1)
else:
dicts[nums[i]] = i + 1

LeeCode 1-Two Sum的更多相关文章

  1. leecode系列--Two Sum

    学习这件事在任何时间都不能停下.准备坚持刷leecode来提高自己,也会把自己的解答过程记录下来,希望能进步. Two Sum Given an array of integers, return i ...

  2. leecode 每日解题思路 64 Minimum Path Sum

    题目描述: 题目链接:64 Minimum Path Sum 问题是要求在一个全为正整数的 m X n 的矩阵中, 取一条从左上为起点, 走到右下为重点的路径, (前进方向只能向左或者向右),求一条所 ...

  3. 树中是否存在路径和为 sum leecode java

    https://oj.leetcode.com/problems/path-sum/ /** * Definition for binary tree * public class TreeNode ...

  4. 算法题思路总结和leecode继续历程

    2018-05-03 刷了牛客网的题目:总结思路(总的思路跟数学一样就是化简和转化) 具体启发点: 1.对数据进行预处理排序的思想:比如8皇后问题 2.对一个数组元素进行比较的操作,如果复杂,可以试试 ...

  5. leecode刷题(8)-- 两数之和

    leecode刷题(8)-- 两数之和 两数之和 描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输 ...

  6. LeeCode(No2 - Add Two Numbers)

    LeeCode是一个有意思的编程网站,主要考察程序员的算法 第二题: You are given two non-empty linked lists representing two non-neg ...

  7. LeetCode - Two Sum

    Two Sum 題目連結 官網題目說明: 解法: 從給定的一組值內找出第一組兩數相加剛好等於給定的目標值,暴力解很簡單(只會這樣= =),兩個迴圈,只要找到相加的值就跳出. /// <summa ...

  8. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  9. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

随机推荐

  1. 百度编辑器(Ueditor)最新版(1.4.3.3)插入锚点失败原因分析及BUG修复

    用百度编辑器——Ueditor(版本1.4.3.3,2016-05-18日上线)插入锚点的时候,每次总是失败,百思不得其解.通过分析Ueditor的代码ueditor.all.js,可以看出Uedit ...

  2. jexus 配置 学习

    http://www.linuxdot.net/ 1.禁止或允许某IP或IP段访问网站 A.只允许某些IP地址访问网站(白名单功能) 默认情况下,允许所有IP地址访问.如果手工设置IP地址白名单, 那 ...

  3. 一款jQuery仿海尔官网全屏焦点图特效代码

    一款jQuery仿海尔官网全屏焦点图特效代码,带有左右箭头的jQuery焦点图切换特效. 当焦点图切换时,下方的三块小图也相对应的进行切换.并且特效还兼容头疼的IE6.赶快去和谐了它吧! 适用浏览器: ...

  4. sublime text3的配置(整理)

    一.代码片段 开发人员很多时候是在做一些重复的工作. 针对不同数据表的增删改查都差不多,重复来重去的.很久不写程序了,利用十一假期在家看看书,写写程序. 最近一直很喜欢使用Sublime Text,发 ...

  5. 应用js改变问章字体大小

    刚来公司的时候领导给分配的都是一些简单的简单的简单的.....任务 一次叫我把文章的字体大小变换功能写出来.在网上搜了很多都不管用!不过功夫不负有心人还是被我找到了!拿出来分享下! <scrip ...

  6. opencv初体验

    http://guoming.me/opencv-config  这篇文章有讲解opencv的安装与配置 一些常用库 opencv_core249d.lib opencv_imgproc249d.li ...

  7. 正确处理WPF中Slider值改变事件的方式

    最近在用WPF数据绑定重写一下播放器项目时遇到的关于Slider的问题,在窗体透明度调节和播放进度调节上用了Slider控件.调节窗体透明度我是 这么想的:将窗体的Opacity属性的值与Slider ...

  8. Redis 代理服务Twemproxy

    1.twemproxy explore 当我们有大量 Redis 或 Memcached 的时候,通常只能通过客户端的一些数据分配算法(比如一致性哈希),来实现集群存储的特性.虽然Redis 2.6版 ...

  9. SQL2012 附加数据库提示5120错误解决方法

    在win8.1 x64系统上使用sql2012进行附加数据库(包括在x86系统正在使用的数据库文件,直接拷贝附加在X64系统中)时,提示无法打开文件,5120错误. 这个错误是因为没有操作权限,所以附 ...

  10. 【Go】 http webserver

    示例1: package main import ( "fmt" "net/http" "encoding/json" ) var i in ...