zoukankan      html  css  js  c++  java
  • 1. 两数之和

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

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

    示例:

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

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


    思路:双指针:
    1. 每一趟遍历的前提:i<j;
    2. i指针从前往后,j指针从后往i;
    3. 遇到满足条件的终止遍历并返回i、j;
     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         # 初始化双指针
     9         i, j = 0, len(nums) - 1
    10         result = []
    11         for i in range(0, len(nums)-1):
    12             while i < j:
    13                 if i < j and target - nums[i] != nums[j]:
    14                     j -= 1
    15                 elif i < j and target - nums[i] == nums[j]:
    16                     result.append(i)
    17                     result.append(j)
    18                     return result
    19             # 重置j指针:每一趟遍历j均从最后往前走
    20             j = len(nums)-1
    21             continue
    22         return result
  • 相关阅读:
    asp之缓存 cachestate
    ASP。net 之view
    ASP.net gridview之性别
    asp的gridview
    yii源码学习心得2
    yii源码学习心得
    什么是伪静态?伪静态有何作用?
    Yii2.0 时间日期插件之yii2-timepicker
    yii中调整ActiveForm表单样式
    8个新鲜的PHP常用代码
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12681797.html
Copyright © 2011-2022 走看看