LeeCode 1-Two Sum
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的更多相关文章
- leecode系列--Two Sum
学习这件事在任何时间都不能停下.准备坚持刷leecode来提高自己,也会把自己的解答过程记录下来,希望能进步. Two Sum Given an array of integers, return i ...
- leecode 每日解题思路 64 Minimum Path Sum
题目描述: 题目链接:64 Minimum Path Sum 问题是要求在一个全为正整数的 m X n 的矩阵中, 取一条从左上为起点, 走到右下为重点的路径, (前进方向只能向左或者向右),求一条所 ...
- 树中是否存在路径和为 sum leecode java
https://oj.leetcode.com/problems/path-sum/ /** * Definition for binary tree * public class TreeNode ...
- 算法题思路总结和leecode继续历程
2018-05-03 刷了牛客网的题目:总结思路(总的思路跟数学一样就是化简和转化) 具体启发点: 1.对数据进行预处理排序的思想:比如8皇后问题 2.对一个数组元素进行比较的操作,如果复杂,可以试试 ...
- leecode刷题(8)-- 两数之和
leecode刷题(8)-- 两数之和 两数之和 描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输 ...
- LeeCode(No2 - Add Two Numbers)
LeeCode是一个有意思的编程网站,主要考察程序员的算法 第二题: You are given two non-empty linked lists representing two non-neg ...
- LeetCode - Two Sum
Two Sum 題目連結 官網題目說明: 解法: 從給定的一組值內找出第一組兩數相加剛好等於給定的目標值,暴力解很簡單(只會這樣= =),兩個迴圈,只要找到相加的值就跳出. /// <summa ...
- 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 ...
- Leetcode 笔记 112 - Path Sum
题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...
随机推荐
- WIN2003跳出res://C:WINDOWSsystem32mys.dll/mys.hta解决方法
出现这个问题的时候 @echo off 请将以下语句复制到记事本中,另存为后缀为.cmd的文件,并运行.当然在命令行下一句句运行也没问题. echo 正在修复,这个过程可能需要几分钟,请稍候…… ru ...
- AngularJS(16)-路由
AngularJS 路由 本章节我们将为大家介绍 AngularJS 路由. AngularJS 路由允许我们通过不同的 URL 访问不同的内容. 通过 AngularJS 可以实现多视图的单页Web ...
- DevExpress12.2.6 安装顺序记录
环境DelphiXE,实测DevExpress手工安装顺序: 1.ExpressCore Library 2.XP Theme Manager 3.ExpressGDI+ Library 4.Expr ...
- selenium-webdriver用例批量运行和测试套件使用 ------之我见
用例批量运行和测试套件使用 ------之我见 学习selenium-webdriver已经一段时间了,最近学习到,测试用例的批量执行,和测试套件的使用,有点自己的理解,不晓得对不对,希望大家指正! ...
- 通过keepalived实现 MySQL VIP 自动切换
首先配置keepalived.链接如下:http://blog.itpub.net/28939273/viewspace-1808369/ 主服务器keepalived的配置文件内容如下: [root ...
- swift UIAlertController教程
在iOS8中,UIAlertView与UIActionSheet都已经退休,取而代之的是UIAlertController!它的使用示范如下://弹出一个警告框,标题是“提示”,信息是“我的博客:oa ...
- java常用集合类:Deque,ArrayList,HashMap,HashSet
图一:java collection 类图 Queue家族 无论是queue还是stack,现在常用的是Deque的实现类:如单线程的ArrayQueue,多线程的ArrayBlockingQueue ...
- VBS基础篇 - Err对象
Err对象是一个具有全局范围的内部对象,含有关于错误的所有信息.On Error Resume next 忽略运行时产生的所有错误On Error Goto 0 取消忽略错误措施主要方法有:Clear ...
- linux第四周作业
一.用户态内核态与中断 1.库函数把内核调用封装起来. 2.区分内核态和用户态是为了让系统更稳定.Linux里吧用户态定位3级,把内核态定位0级. 3.中断处理就是从用户态进入内核态的主要方法,系统调 ...
- select 取值
select 标签是下拉列表标签.在网站中使用很多. 在后台服务器标记的下拉框在前台都会生成select标签. 他的子项就是option标签.要确认一个项是否被选中,就要确定子项中的selected标 ...