zoukankan      html  css  js  c++  java
  • leetcode-001-Two sum

    一、问题描述

    二、解题思路

    这道题:exactly one solution,所以:1)不必考虑多解情况;2)不必考虑无解的异常处理。

    方法一:暴力搜索

    直接依次进行比较,时间复杂度O(n2):

    class Solution:
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            for m,x in enumerate(nums[0:-1]):
                for n,y in enumerate(nums[(m+1):]):
                    res = (target-y)
                    if x == res:
                        return m,n+m+1
    

      用时过长:

     当然也可以先排序,再利用首/尾移动查找,复杂付O(n*logn)

    方法二:哈希表(O(n)

    class Solution(object):
        def twoSum(self, nums, target):
            buff_dict = {}
            for i in range(len(nums)):
                if nums[i] in buff_dict:
                    return [buff_dict[nums[i]], i]
                else:
                    buff_dict[target - nums[i]] = i
    

     

    class Solution(object):
        def twoSum(self,nums, target):
            dic = dict(((v, i) for i, v in enumerate(nums)))
            return next(( (i, dic.get(target-v)) 
                for i, v in enumerate(nums) 
                    if dic.get(target-v, i) != i), None)
    

    class Solution:
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            dic = {}
            for n,x in enumerate(nums):
                try:
                    return dic[x] , n
                except KeyError:
                    dic.setdefault(target - x,n)

    知识点

    • 在读取dict的key和value时,如果key不存在,就会触发KeyError错误
    • 利用next或者for进行遍历,迭代器对象从第一个元素开始访问,直到所有的元素被访问完结束,迭代器只前进不后退。
    • 生成字典:
      • dic = dict(((v, i) for i, v in enumerate(nums)))
      • dic.setdefault(target - x,n)
    • 位置1到末尾:enumerate(nums[0:-1]) 
  • 相关阅读:
    重点词笔记
    pycharm tips
    标注精简过的问题如何导入问题库
    增加权重
    word2vec训练出来的相似词歧义
    算法测试及对比度进一步增强
    Python 命名笔记
    债务重组的会计处理方法
    实质性方案与综合性方案的区别
    什么叫认定层次
  • 原文地址:https://www.cnblogs.com/xingshansi/p/6872816.html
Copyright © 2011-2022 走看看