问题描述

给定一个整数数组, 返回两个数字的索引, 使两个数字相加为到特定值。

您可以假设每个输入都有一个解决方案, 并且您不能使用相同的元素两次。

方法 1: 蛮力

蛮力方法很简单。循环遍历每个元素 xx 并查找是否有另一个值等于目标 xtarget−x。

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

方法2: 哈希表

为了提高运行时速度, 我们需要一种更有效的方法来在数组中查找变量。维护数组中每个元素的映射到其索引的最佳方法是什么?哈希表。

class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashDict = {}
for i in range(len(nums)):
x = nums[i]
if target-x in hashDict:
return (hashDict[target-x], i)
hashDict[x] = i

此方法,在速度排行打败57%的方案

参考

https://stackoverflow.com/questions/30021060/two-sum-on-leetcode

LeetCode Two Sum 解题思路(python)的更多相关文章

  1. [LeetCode] Minimum Size Subarray Sum 解题思路

    Given an array of n positive integers and a positive integer s, find the minimal length of a subarra ...

  2. [LeetCode] Word Break 解题思路

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...

  3. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  4. [LeetCode] Maximum Gap 解题思路

    Given an unsorted array, find the maximum difference between the successive elements in its sorted f ...

  5. Leetcode 34 Find First and Last Position of Element in Sorted Array 解题思路 (python)

    本人编程小白,如果有写的不对.或者能更完善的地方请个位批评指正! 这个是leetcode的第34题,这道题的tag是数组,需要用到二分搜索法来解答 34. Find First and Last Po ...

  6. [LeetCode] Distinct Subsequences 解题思路

    Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...

  7. [LeetCode] Decode Ways 解题思路

    A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' - ...

  8. LeetCode: Path Sum 解题报告

    Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi ...

  9. [LeetCode] Interleaving String 解题思路

    Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example,Given:s1 = ...

随机推荐

  1. Codeforces - 570D 离散DFS序 特殊的子树统计 (暴力出奇迹)

    题意:给定一棵树,树上每个节点有对应的字符,多次询问在\(u\)子树的深度为\(d\)的所有节点上的字符任意组合能否凑成一个回文串 把dfs序存储在一个二维线性表中,一个维度记录字符另一个维度记录深度 ...

  2. 离散化test

    #include<bits/stdc++.h> using namespace std; const int maxn = 1e6+11; int ll[maxn],rr[maxn],ma ...

  3. maven-eclipse-plugin downloadSources downloadJavadocs

    <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclip ...

  4. Linq 与 Lambda 简单使用

    //Lambda表达式详解 //int //List<int> numbers = new List<int> {1,2,3,4,5,6,7,8,9 }; //var n = ...

  5. IOS下去掉input submit圆角和背景色错误

    在iOS系统下input submit会有圆角,如果添加有背景色,背景色错误,在安卓系统是没有这些问题,可以在input样式加上这段样式 input{ -webkit-appearance: none ...

  6. Map接口常用实现类学习

    HashMap 1.6的HashMap:数组加单向链表结构 最重要的内部类Entry,全类名是java.util.HashMap.Entry,是个静态类,实现了Map.Entry接口.HashMap. ...

  7. python 生成嵌套字典

    import collections import json tree=lambda:collections.defaultdict(tree) some_dict=tree() some_dict[ ...

  8. Python-2.7 配置 tab 自动补全功能

    作者博文地址:http://www.cnblogs.com/liu-shuai/ 之前一直使用shell编程,习惯了shell的 tab 自动补全功能,而Python的命令行却不支持 tab 自动补全 ...

  9. Python 断言的使用方法

    自动化测试常用断言的使用方法(python) 自动化测试中寻找元素并进行操作,如果在元素好找的情况下,相信大家都可以较熟练地编写用例脚本了,但光进行操作可能还不够,有时候也需要对预期结果进行判断. 这 ...

  10. Fastjson解析多级泛型的几种方式—使用class文件来解析多级泛型

    Fastjson解析多级泛型 前言 现在网上大多数是使用TypeReference 方式来解析JSON数据,这里我提供另外一种方式来解析,使用类文件进行解析,两种方式我都会给出实际代码 实例 Type ...