• 1. Two Sum


    ref:

    https://blog.csdn.net/linhuanmars/article/details/19711387

    Solution 1:

    time complexity O(1), space complexity O(2)

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            if not isinstance(nums, list) or len(nums) < 2:
                return None
            record = dict()
            idx = 0
            for num in nums:
                rest = target - num
                if rest in record.keys():
                    return record[rest], idx
                record[num] = idx
                idx += 1
            return None
    
    
    print Solution().twoSum([2, 7, 11, 15], 9)

    or time complexity O(n+nlgn) = O(nlgn), space complexity depend on sorting algorithm

    index returned is not correct

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            if not isinstance(nums, list) or len(nums) < 2:
                return None
            nums.sort()
            l, r = 0, len(nums) - 1
            while l < r:
                if nums[l] + nums[r] == target:
                    return nums[l], nums[r]
                elif nums[l] + nums[r] > target:
                    r -= 1
                else:
                    l += 1
            return None
    
    
    print Solution().twoSum([2, 7, 11, 15], 9)
  • 相关阅读:
    test1
    servlet的生命周期
    关与JdbcTemplate"的thread "main" org.springframework.jdbc.BadSqlGrammarException
    正则表达式
    @Autowired和@Resource的区别
    kubernetes安装
    docker相关
    KIBANA
    mysql在centos上安装
    MySql不错的文章
  • 原文地址:https://www.cnblogs.com/geeklove01/p/9306156.html
Copyright © 2020-2023  润新知