Advertisement

Python解法

阅读量:

题干:

对于一个整数数组,返回两个数的索引,使得它们的和等于特定的目标值。

可以假设每个输入都恰好存在一个解,并且不能重复使用同一个元素两次。

示例:

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

由于 nums[0] + nums[1] = 2 + 7 = 9,

因此返回 [0, 1]。

接下来将总结解决这道题目的多种思路,并附上各方法的耗时情况及分析。

注:由于 LeetCode 平台不同时段的运行时间存在较大差异,本次测试操作时间为2018年11月11日左右。

解法一:

复制代码
 class Solution(object):

    
     def twoSum(self, nums, target):
    
     """
    
     :type nums: List[int]
    
     :type target: int
    
     :rtype: List[int]
    
     """
    
     array_len = len(nums)
    
     for i in range(0, array_len-1):
    
         for j in range(i+1, array_len):
    

全部评论 (0)

还没有任何评论哟~