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
     
  • 相关阅读:
    微软与谷歌盈利模式对比分析
    unity开源移动库iTween使用完整Demo
    开发过程遇到的问题和解决方法(备忘)
    微信开发基础教程
    WorkFlow基础实战
    操作系统学习笔记
    编译原理学习
    微信生态圈盈利模式分析
    数据与计算机通信学习笔记
    利用Spring.Net技术打造可切换的分布式缓存读写类
  • 原文地址:https://www.cnblogs.com/yancea/p/7510679.html
Copyright © 2011-2022 走看看