[LeetCode&Python] Problem1: Two Sum

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:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
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:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n=len(nums)

        for j in range(n):
            for i in range(j+1,n):
                if nums[j]+nums[i]==target:
                    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.

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n=len(nums)

        d={}

        for x in range(n):
            a = target-nums[x]
            if nums[x] in d:
                return d[nums[x]],x
            else:
                d[a]=x

  

原文地址:https://www.cnblogs.com/chiyeung/p/9532353.html

时间: 2024-10-04 23:56:51

[LeetCode&Python] Problem1: Two Sum的相关文章

[Leetcode][Python]40: Combination Sum II

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 40: Combination Sum IIhttps://oj.leetcode.com/problems/combination-sum-ii/ Given a collection of candidate numbers (C) and a target number (T),find all unique combinations in C where the candi

[Leetcode][Python]39: Combination Sum

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 39: Combination Sumhttps://oj.leetcode.com/problems/combination-sum/ Given a set of candidate numbers (C) and a target number (T),find all unique combinations in C where the candidate numbers

[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 left leaves in the binary tree, with values 9 and 15 respectively. Return 24. # Definition for a binary tree node. # class TreeNode(object): # def __init__

leetcode python 1.Two Sum

1 class Solution(object): 2 def twoSum(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 d = {}# 新建一个字典存放 key为nums中的值 value为nums中值对应的序号 9 size = 0 10 while size < len(nums):

Leetcode 1191 K-Concatenation Maximum Sum 动态规划

Leetcode 1191 K-Concatenation Maximum Sum 动态规划 题目描述 Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum s

LeetCode --- 64. Minimum Path Sum

题目链接:Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 这道题的要求是在m*n

【Leetcode】Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 思路:简单的动态规划题目,设f(m, n)为从(0, 0)到达(m

leetcode --day12 Surrounded Regions &amp; Sum Root to Leaf Numbers &amp; Longest Consecutive Sequence

1.  Surrounded Regions Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. For example, X X X X X O O X X X O X X O X X After running your fu

leetcode 练习1 two sum

leetcode 练习1  two sum [email protected] 问题描述 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. Example: Given nums = [2, 7, 11, 15