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]    
  • 相关阅读:
    《将博客搬至CSDN》
    所谓找链表中点
    虚函数
    编辑距离
    数组移位
    DFA
    Single Number III
    XOR异或解惑
    First Bad Version
    while(!in.empty()) 和 while(in.size())
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8447475.html
Copyright © 2011-2022 走看看