zoukankan      html  css  js  c++  java
  • 2-1

    题目:

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

    你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

    示例:

    给定 nums = [2, 7, 11, 15], target = 9

    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    代码:

     1 class Solution(object):
     2     def twoSum(self, nums, target):
     3         """
     4         :type nums: List[int]
     5         :type target: int
     6         :rtype: List[int]
     7         """
     8         length = len(nums) - 1
     9         nums_origin = nums
    10         nums = sorted(nums)
    11         while nums[length] // 2 >= target/2 and length != 0:
    12             length //= 2
    13         length //= 2
    14         result = []
    15         s = True
    16         while s:
    17             for i in range(length):
    18                 if nums[i] + nums[length-1] == target and i != length-1:
    19                     j = 0
    20                     for num in nums_origin:
    21                         if num == nums[i] or num == nums[length-1]:
    22                             result += [j]
    23                         j += 1
    24                     return result
    25             length += 1
    26             if length == len(nums)+1:
    27                 s = False
  • 相关阅读:
    正课day04
    正科day03
    正课day02
    正课day01
    预科day08
    Elasticsearch之-文档操作
    Elasticsearch之-映射管理
    Elasticsearch之-索引操作
    Elasticsearch之-倒排索引
    es安装官方,第三方插件
  • 原文地址:https://www.cnblogs.com/tbgatgb/p/11056272.html
Copyright © 2011-2022 走看看