leetcode-两数相加

我只是一个虾纸丫 提交于 2020-03-01 21:23:26

两数之和
(1)迭代法:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        num_index = {}
        for index, num in enumerate(nums):
            if target - num in num_index:
                return [num_index[target - num], index]
            num_index[num] = index
        return []
   (2)暴力解决

时间复杂度:O(n^2)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:   
        length = len(nums)
        # i/j 都是位置索引
        for i, value in enumerate(nums):
            diff = target - value  # 得到差值(:在余下的元素中找到该diff值即可)
            j = i + 1 # 因为不能重复利用同个元素, 所以把'位置索引j'加上1
            while j < length: # +-1问题: 不能取到length
                if nums[j] == diff:
                    return [i, j]
                j += 1

(3)先排序+首尾递进查找
时间复杂度:o(nlogn+n)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        sorted_id_lst = sorted(range(len(nums)), key=lambda x: nums[x]) # 记录排序后的位置索引(不会真的对原nums排序)
        left_point = 0 # 记录左边的索引位置
        right_point = len(nums) - 1 # 记录右边的索引位置
        while left_point < right_point:  # 当左边索引位==右边索引位时,退出循环(没有找到target)
            sum = nums[sorted_id_lst[left_point]] + nums[sorted_id_lst[right_point]] # sorted_id_lst是索引位的列表, 取值方法略繁琐
            if sum == target:
                return [sorted_id_lst[left_point], sorted_id_lst[right_point]]
            elif sum < target:
                left_point += 1
            elif sum > target:
                right_point -= 1

(4)哈希法
时间复杂度:O(n)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for i, value in enumerate(nums):
            diff = target - value
            if diff in hashmap:
                return [hashmap.get(diff), i] # i应该放在后面的位置
            hashmap[value] = i # 如果hashmap中没有diff值, 则把value作为键/位置索引作为值赋给hashmap(注意位置别颠倒)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!