美文网首页
刷题笔记06-19 (2)

刷题笔记06-19 (2)

作者: 不务正业的码农 | 来源:发表于2018-06-20 11:58 被阅读0次

经典的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].


第一种解法 利用散列表

时间复杂度O(n),空间复杂度O(n)
解题思路:
比较直接的解题思路,遍历数组的所有元素x,查找是否有值匹配target - x。利用散列表查找时间复杂度为O(1)
我们可以将查找匹配值的时间复杂度下降到O(n),相应的,因为我们建立映射表,所以空间复杂度提升到了O(n)

def twoSum(nums,target):
    result = []
    dict1 = {}
    for i in range(0,len(nums)):
        dict1[nums[i]] = i # build the mapping between the nums elements and its index
    for n in range(0,len(nums)):
        the_other = target - nums[n] 
        if the_other in dict1 and dict1[the_other] != n:# make sure we don't find the same value
            result.append(n)
            result.append(dict1[the_other])
            # if we return result outside the loop, we may get duplicate index as we loop through twice the same combinations
            return result 

第二种解法 暴力算法

时间复杂度O(n**2),空间复杂度O(n)
解题思路,没啥好说的。

def twoSum(self, nums, target):
        result = []
        for i in range(0,len(nums)):
            mama = target - nums[i]
            for j in range(0,len(nums)):
                if nums[j] == mama and j != i:
                    result.append(i)
                    result.append(j)
                    return result

相关文章

  • 刷题笔记06-19 (2)

    经典的Two Sum问题 题目如下 Given an array of integers, return indi...

  • 刷题笔记06-19 (1)

    括号匹配(栈思想) 题目如下 Given a string containing just the charact...

  • 晨间日记

    计算机刷题 看书写笔记 高数刷题 英语刷题 奋斗到天亮,加油奥利给

  • 谷歌工程师为金三银四筹备1000道Leetcode刷题笔记

    对于刷题相关的文章,在之前我也推荐过不少,今天再给大家推荐一份算法刷题笔记,这份笔记与以往的刷题有所区别,作者把 ...

  • 刷题笔记

    算法思想 一、二分查找 1. 算法思想 算法详解 算法细节 一定要看二分查找细节.md 实现时需要注意以下细节: ...

  • 刷题笔记

    最近在准备面试,发现自己真的菜的不行,就计划接下来的时间把 leetcode 上面刷的 中等题 和 每日一题做个简...

  • 刷题笔记

    题目描述 343 - Integer BreakGiven a positive integer n, break...

  • 4.8日计划

    1.听课,做笔记。 2.做学习强国题,读笔记知识点。 3.刷20道题。 4.晚上睡觉前回顾,复盘今日所学。 坚持,...

  • 4.10日计划

    一早打开番茄钟,防止刷手机,提早进入学习状态。 1.听课,做笔记。 2.做学习强国题,读笔记知识点。 3.刷20道...

  • 2020-01-16 - 草稿

    梁桉1月16日工作日报 一、工作内容 1. 刷题 2.记笔记 3.写逐字稿练课 二、工作心得 今天在刷题的过程中,...

网友评论

      本文标题:刷题笔记06-19 (2)

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