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

    题目

    给你一个列表nums和一个数字target,如果列表里面有两个数之和等于target,则返回两个数字的下坐标,这两个数不能为同一个数。(假设总会有这两个数)

    python

    时间复杂度O(n^2)

    # -*- coding:utf-8 -*-
    
    class Solution(object): # O(n^2)
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            for num in nums:
            	i = nums.index(num)
            	j = [j for j,v in enumerate(nums) if v==(target-num) and j!=i]
            	if j:
            		return [i, j[0]]
    
    s = Solution()
    print(s.twoSum([0, 4, 3, 0], 0))
    

    时间复杂度O(n)

    # -*- coding:utf-8 -*-
    
    class Solution(object): # O(n)
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            map = {}
            for index, num in  enumerate(nums):
                if num in map:
                    return [map[num], index]
                else:
                    map[target-num] = index
    
                    
    s = Solution()
    print(s.twoSum([0, 4, 3, 0], 0))
    
  • 相关阅读:
    第二章、Redis入门介绍
    最高的牛
    增减序列
    激光炸弹
    分形之城
    约数之和
    奇怪的汉诺塔
    费解的开关
    递归实现排列型枚举
    递归实现组合型枚举
  • 原文地址:https://www.cnblogs.com/sinanorz/p/7636092.html
Copyright © 2011-2022 走看看