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

 

posted @ 2019-06-20 01:56  mingyu02  阅读(242)  评论(0编辑  收藏  举报