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. mongodb 3.x WiredTiger存储优化测试

    http://pan.baidu.com/s/1sk8zekX 总结:1.使用WiredTiger引擎压缩比例约是MMAP引擎的12倍,2.从时间上看,此次测试100个线程并发,mongodb 3.2 ...

  2. linux gd库不支持jpeg解决办法

    1. 查看gd库是否支持jpeg gd_info(); 2. 如果JPEG Support 不为1则不支持. 3.首先下载 libjpeg http://www.ijg.org/ ,进行安装 安装目录 ...

  3. 判断php数组维度的小例子

    分享一例判断php数组维度的代码,供大家参考. 如下所示: <?php /** * 返回数组的维度 * @param [type] $arr [description] * @return [t ...

  4. Spark 大数据平台

    Apache Spark is an open source cluster computing system that aims to make data analytics fast - both ...

  5. linux设备驱动模型

    尽管LDD3中说对多数程序员掌握设备驱动模型不是必要的,但对于嵌入式Linux的底层程序员而言,对设备驱动模型的学习非常重要. Linux设备模型的目的:为内核建立一个统一的设备模型,从而又一个对系统 ...

  6. self,parent,this区别

    我容易混淆public,private,protected,还容易混淆this,self这些东西.前面已经写了一篇关于public,private,protected博文了,下面来说一下this,se ...

  7. windows 2008 怎么对外开放端口

    服务器已经运行了程序,但是android客户端连接不上, 网上提示说用: start /min telnet 192.168.3.42 2121 查看,但是我的提示tenlet找不到命令,估计是端口的 ...

  8. android开发获取屏幕高度和宽度

    宽度:getWindowManager().getDefaultDisplay().getWidth(); 高度:getWindowManager().getDefaultDisplay().getH ...

  9. 解决在ubuntu下requests 无法找到模块packages

    我明明用pip install requests安装成功了,但是依然报下面的错 错误1 requests.packages.urllib3.disable_warnings()AttributeErr ...

  10. 邻结矩阵的建立和 BFS,DFS;;

    邻结矩阵比较简单,, 它的BFS,DFS, 两种遍历也比较简单,一个用队列, 一个用数组即可!!!但是邻接矩阵极其浪费空间,尤其是当它是一个稀疏矩阵的时候!!!-------------------- ...