用Python3实现LeetCode算法题系列——No.01 Two Sum [Easy]

版权声明:转载请注明来源! https://blog.csdn.net/CAU_Ayao/article/details/81191194

目录


题目

>> 英文版本
      Given an array of integers, return indices of the two numbers such that they add up to a specific target.
      You may assume that each input would have exactly one solution, and you may not use the same element twice.
>> 中文版本
      给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
      你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

例子(Example)

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

提交的代码

i = 0
j = 0
target = int(target)
    for i in range(0,len(nums)):
        for j in range(i+1,len(nums)):
            if nums[i] + nums[j] == target:
                return i,j
                break  

运行效果

这里写图片描述
这里写图片描述

相关知识点

>> self参数
      类似于C++中类里面的this指针,指对象自身。
      推荐参考:一篇文章让你彻底搞清楚Python中self的含义
>> range函数
      range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。
      list() 函数是对象迭代器,可以把range()返回的可迭代对象转为一个列表,返回的变量类型为列表。
      推荐参考:Python3 range() 函数用法

完整代码

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        i = 0
        j = 0
        target = int(target)
        for i in range(0,len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] + nums[j] == target:
                    return i,j
                    break

def stringToIntegerList(input):
    return json.loads(input)

def integerListToString(nums, len_of_list=None):
    if not len_of_list:
        len_of_list = len(nums)
    return json.dumps(nums[:len_of_list])

def main():
    import sys
    def readlines():
        for line in sys.stdin:
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            nums = stringToIntegerList(line);
            line = next(lines)
            target = int(line);

            ret = Solution().twoSum(nums, target)

            out = integerListToString(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/CAU_Ayao/article/details/81191194