美文网首页
LeetCode系列【1】

LeetCode系列【1】

作者: 克里斯托弗的梦想 | 来源:发表于2019-04-07 10:01 被阅读0次

目前想根据GitHub上的LeetCode的整理,打算每天练几道题,增加自己的编程能力,当成课外习题去学习,希望能够有所进步和提升。

原题连接: https://leetcode.com/problems/two-sum

内容描述:

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].

解题方案
1、暴力解法,两轮遍历

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

上面的思路1太慢了,我们可以牺牲空间换取时间
2、时间复杂度: O(N),空间复杂度: O(N)

  • 建立字典 lookup 存放第一个数字,并存放该数字的 index
  • 判断 lookup 中是否存在: target - 当前数字, 则表面当前值和 lookup中的值加和为 target.
  • 如果存在,则返回: target - 当前数字的index和当前值的index
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype List[int]
        """
        lookup = {}
        for i, num in enumerate(nums):
            if target - num in lookup.keys():
                return [lookup[target-num], i]
            else:
                lookup[num] = i

相关文章

  • LeetCode系列【1】

    目前想根据GitHub上的LeetCode的整理,打算每天练几道题,增加自己的编程能力,当成课外习题去学习,希望能...

  • Leetcode - 买卖股票最佳时机

    系列题目: Leetcode 121.买卖股票的最佳时机1 【只能交易1次】 Leetcode 122.买卖股票的...

  • python学习纪录

    leetcode刷题系列来源:力扣(LeetCode)链接:https://leetcode-cn.com/pro...

  • Swap Nodes in Pairs

    标签: C++ 算法 LeetCode 链表 每日算法——leetcode系列 问题 Swap Nodes in ...

  • Combination Sum II

    标签: C++ 算法 LeetCode DFS 每日算法——leetcode系列 问题 Combinatio...

  • Divide Two Integers

    标签: C++ 算法 LeetCode 每日算法——leetcode系列 问题 Divide Two Integ...

  • First Missing Positive

    标签: C++ 算法 LeetCode 数组 每日算法——leetcode系列 问题 First Missing...

  • Valid Sudoku

    Valid Sudoku 标签: C++ 算法 LeetCode 每日算法——leetcode系列 问题 Val...

  • Next Permutation

    标签: C++ 算法 LeetCode 数组 每日算法——leetcode系列 问题 Next Permuta...

  • Trapping Rain Water

    标签: C++ 算法 LeetCode 数组 每日算法——leetcode系列 问题 Trapping Rain...

网友评论

      本文标题:LeetCode系列【1】

      本文链接:https://www.haomeiwen.com/subject/eopjiqtx.html