0001_Two_Sum

0001_Two_Sum

Posted by taomujian on November 4, 2020

题目

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

给一个数组和一个整数,返回数组中二个元素之和等于这个整数的元素的索引

思路

首先把这个数组按照索引和值的方式组成一个元组数组,然后按照值的大小对得到的这个数组排序,按照数组长度得到一个循环终止条件,然后循环这个数组,如果二个整数之和为目标,则返回这二个整数的索引

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env python3

class Solution:

    def get_data(self, elem):
        """
        获取元组的最后一个元素
        
        :param tuple elem:  要寻找的元组
        :return int result: 元组的最后一个元素
        """
        
        result = elem[1]
        return result

    def twoSum(self, nums, target):
        """
        寻找数组中二个元素之和为目标的元素的索引
        
        :param list nums: 要寻找的数组
        :param int target: 目标值
        :return list result: 数组中二个元素之和为目标的元素的索引列表
        """

        try:
            nums_index = [(index, value) for index, value in enumerate(nums)]
            nums_index.sort(key = self.get_data)    # 按照元组的最后一个元素排序,默认是按照第一个元素排序
            begin, end = 0, len(nums) - 1
            while begin < end:
                data_sum = nums_index[begin][1] + nums_index[end][1]
                if data_sum == target:
                    result = [nums_index[begin][0], nums_index[end][0]]
                    return result
                elif data_sum < target:
                    begin += 1
                else:
                    end -= 1
        except Exception as e:
            print(e)
        finally:
            pass
        

if __name__ == "__main__":
    solution = Solution()
    print(solution.twoSum([3, 2, 4], 6))