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
     
  • 相关阅读:
    Android应用签名
    Win7环境下TreeSaver编译环境的搭配
    TreeSaver 使用教程整理——Step 4: Using a Title Figure
    使用jquery获取父元素或父节点的方法
    IIS 错误代码分析手册
    敏捷开发 规范
    Asp.net中时间格式化的几种方法
    在Oracle中使用Guid
    jquery 当前时间
    JQuery一种取同级值的方式 比如你在GridView中如下
  • 原文地址:https://www.cnblogs.com/yancea/p/7510679.html
Copyright © 2011-2022 走看看