• 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)
  • 相关阅读:
    Core Data
    scrollViews
    网络通信
    UIView
    textView取消键盘
    AFNetworking转载
    多线程
    css3[转载][菜单导航] 带有记忆功能的多页面跳转导航菜单
    jQuery翻牌或百叶窗效果
    jQuery联动日历(三)完成
  • 原文地址:https://www.cnblogs.com/geeklove01/p/9306156.html
Copyright © 2020-2023  润新知