zoukankan      html  css  js  c++  java
  • 力扣 1. 两数之和--python 每日一题

    给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

    你可以按任意顺序返回答案。

    示例 1:

    输入:nums = [2,7,11,15], target = 9
    输出:[0,1]
    解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
    示例 2:

    输入:nums = [3,2,4], target = 6
    输出:[1,2]
    示例 3:

    输入:nums = [3,3], target = 6
    输出:[0,1]
     

    提示:

    2 <= nums.length <= 103
    -109 <= nums[i] <= 109
    -109 <= target <= 109
    只会存在一个有效答案

     O(n2):

    class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            L=[]
            for i in range(len(nums)):
                for j in range(len(nums)):
                    if i != j and nums[i]+nums[j]==target:
                        L.append(i)
            return L

     O(n):

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            for i in range(len(nums)):
                if target-nums[i] not in nums:
                    continue
                elif target-nums[i] in nums and i != nums.index(target-nums[i]):
                    return [i,nums.index(target-nums[i])]
    晚生不才,请多指教!
  • 相关阅读:
    实验二、作业调度模拟实验
    实验一
    0909 初识操作系统
    实验四、主存空间的分配和回收模拟
    12.27评论5位同学试验三
    实验三进程调度模拟程序
    实验二、作业调度模拟实验
    实验一报告
    实验四 主存空间的分配和回收模拟
    实验三 进程调度模拟程序
  • 原文地址:https://www.cnblogs.com/lkc-test/p/14678599.html
Copyright © 2011-2022 走看看