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. 【Sharing】如何成为一名黑客

    [声明]此文为转载,只为收藏. 从小到大听说了无数关于“电脑黑客”的故事,比如XXX入侵美国五角大楼,再比如前几年的“熊猫烧香”病毒,这些故事的主角都被我们的媒体称之为“黑客”.其实这些人,更大程度上 ...

  2. visifire3.6.8 去水印方法

    visifire 很NB的一套开源图表 不多介绍 详询google 3.0以下版本可以直接继承Chart类 override 加水印的函数就可以, 3.0以上版本需要自己编译源代码 这个水印函数藏得有 ...

  3. hdu 5690 2016"百度之星" - 初赛(Astar Round2A) All X 快速二次幂 || 寻找周期

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5690 题意:m个数字全为x mod k ?= c;其中m <= 1010,0 < c,k ...

  4. linux设备驱动模型

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

  5. 收起虚拟键盘的各种方法 -- IOS

    使用虚拟键盘来输入资讯,是 iOS 的重要互动方式之一,虚拟键盘通常会自动出现在可以编辑的 UITextField 或是 UITextView 的编辑事件中,叫出键盘固然容易,但是要把它收起来,可就没 ...

  6. 2016 系统设计第一期 (档案一)MVC bootstrap model弹出子页面

    通过bootstrap  弹出modal-dialog 子页面 ,例如我要弹出子页面:areaitem_sub_One.html. 具体步骤如下: 第一步:新建 areaitem_sub_One.ht ...

  7. php获取指定日期所在星期的开始时间与结束时间

    function getWeekRange($date){    $ret=array();    $timestamp=strtotime($date);    $w=strftime('%u',$ ...

  8. 【学习总结】【多线程】 安全隐患 & 通讯 & 线程的状态

    一.多线程的安全隐患 资源共享 1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源 比如多个线程访问同一个对象.同一个变量.同一个文件 当多个线程访问同一块资源时,很容易引发数据错乱和数 ...

  9. python3 学习总结与建议

    最近我又玩起了python,以前听说过它,只是那时候我看见官方的一句名言:“用python语言编程,只用一种最好的方式去实现就可以了”,我就对它提不起兴趣了.原因是我是一个喜欢自由的人,不喜欢做事情只 ...

  10. 2463: [中山市选2009]谁能赢呢?- BZOJ

    Description小明和小红经常玩一个博弈游戏.给定一个n×n的棋盘,一个石头被放在棋盘的左上角.他们轮流移动石头.每一回合,选手只能把石头向上,下,左,右四个方向移动一格,并且要求移动到的格子之 ...