zoukankan      html  css  js  c++  java
  • 1. Two Sum

    https://leetcode.com/articles/two-sum/#approach-2-two-pass-hash-table-accepted

    Question

    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.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    Solution

    Approach #1 (Brute Force)

    Loop through each element x and find if there is another value that equals to target - x.

    Time complexity : O(n^2)O(n2​​)

    Space complexity : O(1)O(1).

    Approach #2 (Two-pass Hash Table)

    A simple implementation uses two iterations. In the first iteration, we add each element's value and its index to the table. Then, in the second iteration we check if each element's complement (target - nums[i]) exists in the table. Beware that the complement must not be nums[i] itself!

    • Time complexity : O(n). We traverse the list containing nn elements exactly twice. Since the hash table reduces the look up time to O(1), the time complexity is O(n).

    • Space complexity : O(n). The extra space required depends on the number of items stored in the hash table, which stores exactly nn elements.

    Approach #3 (One-pass Hash Table) 

     While we iterate and inserting elements into the table, we also look back to check if current element's complement already exists in the table. If it exists, we have found a solution and return immediately.

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            seen = {} # use dictionary data structure
            for i in range(len(nums)): # i is the position/key of the num
                num2 = target - nums[i]  # num2 is the value
                if num2 in seen: # num2 is the key
                    return [seen[num2], i]
                else:
                    seen[nums[i]] = i
            return 'Not found'

    Complexity Analysis:

    • Time complexity : O(n). We traverse the list containing nn elements only once. Each look up in the table costs only O(1)time.

    • Space complexity : O(n). The extra space required depends on the number of items stored in the hash table, which stores at most n elements.

    Plus,

    If the question only asks us to find out the two elements themselves, rather their indices, the set() data structure in python can help us out.

    "

    For this problem we will take advantage of a set data structure. We will make a single pass through the list of integers, treating each element as the first integer of our possible sum.

    At each iteration we will check to see if there is a second integer which will allow us hit the target number, adn we will use a set to check if we've already seen it in our list.

    We will then update our seen set by adding the current number in the iteration to it.

    "

    def solution(lst,target):
        
        # Create set to keep track of duplicates
        seen = set()
        
        # We want to find if there is a num2 that sums with num to reach the target
        
        for num in lst:
            
            num2 = target - num
            
            if num2 in seen:
                return [num2, num]
            
            seen.add(num)
            
        # If we never find a pair match which creates the sum
        return False

    def twosum(nums,target):
        seen = {}
        for i in range(len(nums)):
            num2 = target - nums[i]
            if num2 in seen:
                return  [seen[num2] +1 , i + 1]
            seen[nums[i]] = i
        return 'Not Found'
        
        
    nums = [4, 2, 1, 5, 7]
    target = 12
    print twosum(nums,target

     

    Note:

    1 Seen is a dictionary, use {} not [] 

    2 The problem requires us to output the index(position) of elements. When using the dictionary data structure, the key should be the element, and the value should the index. Also note we campare if the element is in the dictionary seen, that's what keys do.

    We search keys to get values

  • 相关阅读:
    vue-学习笔记-事件处理
    微博api接口登陆,获取信息,分享微博
    ad批量上传
    jieba分词及词频统计小项目
    Python内置函数复习
    爬虫哈希破解密码
    pipenv 管理虚拟环境
    python工程化最佳实践
    matplotlib绘图难题解决
    pandas 实现rfm模型
  • 原文地址:https://www.cnblogs.com/prmlab/p/6888767.html
Copyright © 2011-2022 走看看