zoukankan      html  css  js  c++  java
  • 28.leetcode167_two_sum_II

    1.题目描述

    Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution and you may not use the same element twice.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2 

    给出一个升序数组和一个目标数字,遍历一次指出相加元素和为目标元素的元素的位置。

    2.题目分析

    双指针操作,分别从头和尾开始遍历,相加和比目标数字小,前指针移动一位;反之,后指针移动一位

    3.解题思路

     1 class Solution(object):
     2     def twoSum(self, numbers, target):
     3         """
     4         :type numbers: List[int]
     5         :type target: int
     6         :rtype: List[int]
     7         """
     8         i=0
     9         j=len(numbers)-1
    10         while i<j: #前指针永远在后指针前面
    11             if target-numbers[j]>numbers[i]: 
    12                 i+=1 #前指针移动
    13                 continue
    14             if target-numbers[j]<numbers[i]:
    15                 j-=1 #后指针移动
    16                 continue
    17             else:
    18                 return [i+1,j+1]    
  • 相关阅读:
    组装树状结构文本框
    在jsp页面动态添加,删除文本框模块
    sql字段拆分 ,连表子查询获取值
    jsp页面技术总结
    C语言的基本数据类型
    如何学习一些需要算法的程序
    如何学习一门新的编程语言
    C++ 预处理器
    C++ 函数模板&类模板
    C++ 文件和流
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8447475.html
Copyright © 2011-2022 走看看