美文网首页
Two sum-Leetcode Day 1

Two sum-Leetcode Day 1

作者: 码力平平菜鸡熊 | 来源:发表于2019-01-21 21:14 被阅读0次

    1. 问题描述

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution, and you may not use the same element twice.

    2. 解法

    2.1 暴力搜索

    class Solution:
        def twoSum(self, nums, target):
            L = []
            for i in range(0, len(nums)):
                for j in range(i, len(nums)):
                    if(i!=j and nums[i] + nums[j] == target and ((target%2 == 0 and nums[i]%2==nums[j]%2) or (target % 2 !=0 and (nums[i]%2)^(nums[j]%2)))):
                        L.append(i)
                        L.append(j)
                        return L
    
    

    对奇偶和两个数满足的条件进行了筛选,时间复杂度仍为O(n^{2})

    2.2 Hash Table查找(One pass)

    2.2.1 思路

    依次遍历List,游标为index。将target-List[index]的值存在字典中,继续查找List,如果随后List中的元素出现在字典的Key中,说明找到了List的当前元素和之前遍历过的元素的配对,进而返回对应的列表[dict[nums[index]], index];Two pass的做法是先构造一个完整的字典,再进行对应的Hash Table的查找,时空复杂度依旧不变。

    import time
    class Solution:
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            dict = {}
            for index in range(len(nums)):
                if nums[index] in dict:               
                    return [dict[nums[index]], index]
                else:
                    dict[target-nums[index]] = index
            print(dict)
    

    2.2.2 复杂度分析

    只对列表遍历了一遍,时间复杂度为O(n), 同时构造了一个字典(Hash Table),空间复杂度是O(n), 属于空间换时间的做法。

    相关文章

      网友评论

          本文标题:Two sum-Leetcode Day 1

          本文链接:https://www.haomeiwen.com/subject/ejqzhqtx.html