LeetCode1-两数之和

最近为了参加CCF考试

开始在pyhton的IDLE编辑器上面写代码了

还在适应中

因为确实是没有pycharm方便啊

Python的许多方便快捷的内置函数都得自己敲

这对自己的业务能力也提出了更高的要求

也挺好的

能让自己对代码有个更清楚的认识!


1-两数之和

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

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

示例:

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

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

思路:

这一题也还是介绍两种方法。第一种是大家最熟悉的暴力法,两层循环遍历,即可得出答案。

代码如下:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        nums_length = len(nums)
        for one_num in range(nums_length-1):
            for second_num in range(one_num+1, nums_length):
                if nums[one_num] + nums[second_num] == target:
                        return [one_num, second_num]
                    
                    
if __name__ == '__main__':
    nums = [2, 7, 11, 15]
    target = 9
    solution = Solution()
    result = solution.twoSum(nums, target)
    print(result)

执行效率那自然是不用说了,差的不能再差了,差点要超出时间限制了。

LeetCode1-两数之和

 

方法二:

此方法在方法一的基础上改进了,只需要一层循环即可找出答案。即根据当前遍历得到的元素index,查找target-index是否在剩余数组里出现,如果找得到,则返回其下标值;反之则说明没有该答案。

代码如下:

class Solution(object):
    # 可用一遍遍历,即根据当前遍历得到的元素index,
    # 查找target-index是否在剩余数组里出现
    # 如果找得到,则返回其下标值;反之则说明没有该答案
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        answer = []
        for left_index in range(len(nums)):
            right = target - nums[left_index]
            if right in nums[left_index+1:]:
                nums_right = nums[left_index+1:]
                right_index = nums_right.index(right)+left_index+1
                answer.extend([left_index, right_index])
                break
        return answer


if __name__ == "__main__":
    nums = [-1, -2, -3, -4, -5]
    target = -8
    answer = Solution().twoSum(nums, target)
    print(answer)

执行效率还算不错,在60%左右。

LeetCode1-两数之和

当然了,各位读者要是有更好的方法还请积极分享啊!!!