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)
原文地址:https://www.cnblogs.com/geeklove01/p/9306156.html