zoukankan      html  css  js  c++  java
  • 167. Two Sum II

    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

    思路:
    1.扫描已经排好序的数组,扫描的数据保存在字典中,并判断需要成对的另一个数是否在数组中;
    2.双指针向中心移动;

        由于数组为有序数组,因此利用头尾指针进行处理,头尾元素之和大于目标值,尾指针向前移动, 如果大于目标值,首指针向后移动

    # 利用字典保留已经扫描过的历史数据
    class Solution():
        def twoSum(self, numbers, target):
            """
            :type numbers: List[int]
            :type target: int
            :rtype: List[int]
            """
            dic = {}
            for i, num in enumerate(numbers):
                if (target - num) in dic:
                    return [dic[target - num], i + 1]
                dic[num] = i + 1
    # 双指针
    class Solution():
        def twoSum(self, numbers, target):
            """
            :type numbers: List[int]
            :type target: int
            :rtype: List[int]
            """       
            left, right = 0, len(numbers) - 1
            while left < right:
                if numbers[left] + numbers[right] == target:
                    return [left + 1, right + 1]
                elif numbers[left] + numbers[right] > target:
                    right -= 1
                else:
                    left += 1
     
  • 相关阅读:
    使用unlist将日期型数据的列表转换为向量时,出现的异常
    => in Scala
    Scala Beginner
    .net Core 调用微信Jsapi接口,H5解析二维码
    TextBoxFor控件的扩展---Bootstrap在mvc上的应用
    Dapper Vs Dbentry
    外地手机号码,请在号码前加拨0
    Sql 2012 远程数据库连接
    DbEntry在Vs2012里的配置
    拓展:正则表达式-常用函数
  • 原文地址:https://www.cnblogs.com/yancea/p/7510679.html
Copyright © 2011-2022 走看看