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. Silverlight动画的基本知识、关键帧动画

    基础知识 (一)动画:是快速播放一系列图像(其中每个图像与下一个图像略微不同)给人造成的一种幻觉 (二)动画类型:两类    (1)From/To/By动画:在起始值和结束值之间进行动画处理.     ...

  2. Nginx启动SSL功能,并进行功能优化,你看这个就足够了

    一:开始Nginx的SSL模块 1.1 Nginx如果未开启SSL模块,配置Https时提示错误 nginx: [emerg] the "ssl" parameter requir ...

  3. C++ string的常用功能

    头文件为#include<string> string str,str1; char s[]; str.length和str.size()是一样的功能都是返回当前字符串的大小: str.e ...

  4. jQuery 滑动方法slideDown向下滑动元素

    通过 jQuery可以在元素上创建滑动效果,jQuery slideDown() 方法用于向下滑动元素. jQuery 滑动方法 通过 jQuery,您可以在元素上创建滑动效果. jQuery 拥有以 ...

  5. Tools for Presention

    ZoomIt v4.5 http://technet.microsoft.com/en-us/sysinternals/bb897434.aspx 微软的教师演示工具 主要有放大,画图,倒计时的功能. ...

  6. SQL Server Management Studio Keyboard shortcuts

    一些平时在SQL Server Management Studio 使用到的快捷键 F5 (Ctrl+x)执行选中部分的语句,没有选中则全文执行 Ctrl+L 现实执行计划(估计) Ctrl+M 在运 ...

  7. PIGCMS提示“你的程序为盗版,非法授权,请联系QQ7530782或者8441010”的修复方法

    最近群里又有人发出来微信平台盗版源码这个问题求解决,其实我本人是一直支持正版的,大家有条件的还是购买正好为好,既然有人问我就顺便解决了下,其实很简单,再换个接口就好了,查看了一下是在\PigCms\L ...

  8. verilog逻辑复制

    本文转自:http://www.cnblogs.com/linjie-swust/archive/2012/03/27/FPGA_verilog.html 在FPGA设计中经常使用到逻辑复制,逻辑复制 ...

  9. Java Day 05

    数组第二种定义 数组-遍历 数组操作的核心思想就是对角标的操作: 数组-求最值 1.循环 比较 排序 选择排序 把原始数组分割成了两个数组,至少有一个是有序的 冒泡排序 相邻元素比较 位置置换代码提取 ...

  10. 部署图 Deployment Diagram

    UML部署图描述了一个运行时的硬件结点,以及在这些结点上运行的软件组件的静态视图. 部署图显示了系统的硬件,安装在硬件上的软件,以及用于连接异构的机器之间的中间件. 下面这张图介绍了部署图的基本内容: ...