Problem Description:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

  1. Given nums = [2, 7, 11, 15], target = 9,
  2.  
  3. Because nums[0] + nums[1] = 2 + 7 = 9,
  4. return [0, 1].

Approach 1: Brute Force

At the beginning, I want to use the Brute Froce method to use this problem. Then I write this code:

  1. class Solution:
  2. def twoSum(self, nums, target):
  3. """
  4. :type nums: List[int]
  5. :type target: int
  6. :rtype: List[int]
  7. """
  8. n=len(nums)
  9.  
  10. for j in range(n):
  11. for i in range(j+1,n):
  12. if nums[j]+nums[i]==target:
  13. return j,i

However, this method wastes too much time.

Solution:

A better method to solve this problem is to use a dictionary to store all the pairs' indices.

  1. class Solution:
  2. def twoSum(self, nums, target):
  3. """
  4. :type nums: List[int]
  5. :type target: int
  6. :rtype: List[int]
  7. """
  8. n=len(nums)
  9.  
  10. d={}
  11.  
  12. for x in range(n):
  13. a = target-nums[x]
  14. if nums[x] in d:
  15. return d[nums[x]],x
  16. else:
  17. d[a]=x

  

[LeetCode&Python] Problem 1: Two Sum的更多相关文章

  1. [LeetCode&Python] Problem 167. Two Sum II - Input array is sorted

    Given an array of integers that is already sorted in ascending order, find two numbers such that the ...

  2. [LeetCode&Python] Problem 653. Two Sum IV - Input is a BST

    Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...

  3. [LeetCode&Python] Problem 371. Sum of Two Integers

    Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Exam ...

  4. [LeetCode&Python] Problem 599. Minimum Index Sum of Two Lists

    Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite ...

  5. [LeetCode&Python] Problem 404. Sum of Left Leaves

    Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two l ...

  6. [LeetCode&Python] Problem 682. Baseball Game

    You're now a baseball game point recorder. Given a list of strings, each string can be one of the 4 ...

  7. [LeetCode&Python] Problem 883. Projection Area of 3D Shapes

    On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes. Each ...

  8. [LeetCode&Python] Problem 807. Max Increase to Keep City Skyline

    In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located the ...

  9. 【leetcode❤python】 303. Range Sum Query - Immutable

    #-*- coding: UTF-8 -*- #Tags:dynamic programming,sumRange(i,j)=sum(j)-sum(i-1)class NumArray(object) ...

随机推荐

  1. 【转】MVC form提交实体接收参数时空字符串值变成null

    问题:entity.BZ的值是null,Request.Form["BZ"]的值是空字符串 目标:让entity.BZ的值是空字符串. 解决方法:在实体的BZ属性上加上 [Disp ...

  2. jeasyUI DataGrid 根据屏幕宽度自适应, 改变右侧滚动条Size

    PC浏览器的Datagrid可以显示多几列,但是在手机浏览器时,只能有选择性的显示前几列. $(window).resize(function () { if (document.body.clien ...

  3. 谈一谈JUnit神奇的报错 java.lang.Exception:No tests found matching

    最近在学习Spring+SpringMVC+MyBatis,一个人的挖掘过程确实有点艰难,尤其是有一些神奇的报错让你会很蛋疼.特别是接触一些框架还是最新版本的时候,会因为版本问题出现很多错误,欢迎大家 ...

  4. java基础语法运算符

    1.1                算数运算符++.--的使用 在一般情况下,算数运算符不会改变参与计算的变量值.而是在原有变量值不变的情况下,计算出新的值.但是有些操作符会改变参与计算的变量的值, ...

  5. JAVA工程师面试常见问题集锦

    集锦一: 一.面试题基础总结 1. JVM结构原理.GC工作机制详解 答:具体参照:JVM结构.GC工作机制详解     ,说到GC,记住两点:1.GC是负责回收所有无任何引用对象的内存空间. 注意: ...

  6. day05 可变不可变类型

    #可变类型: 值变了,但是id没有变,证明没有生成新的值而是在改变原值,原值是可变类型#不可变类型:值变了,id也跟着变,证明是生成了新的值而不是在改变原值,原值是不可变 # x=10# print( ...

  7. Introduction to Cryto & Crptocurrencies Lecture 1

    Lecture 1.2 Hash Pointer & Data Structure Use Case 1. 什么是Block Chain呢? 想象一个像链表一样的结构,只不过与通常的指向下一块 ...

  8. Animation(动画)倒着播放方法

    public GameObject AnimationObj;//带有动画的对象 // Use this for initialization void Start () { AnimationObj ...

  9. day02 运算符和编码

    今日所学 主要是运算符和编码的初认识, 1   还有比较运算 ==,!=,<>,>,<,>=,<=等 2  .  赋值运算 =,+=,-=等 还有今天的难点逻辑运算 ...

  10. SpringBoot 上传、下载(四)

    工程目录结构 完整代码: 1.pom.xml 首先当然是添加依赖,用到thymeleaf模板渲染html页面 <project xmlns="http://maven.apache.o ...