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
     
  • 相关阅读:
    BBB-media配置
    BBB-添加文章及文章中图片
    inclusion_tag模块
    BBB-登录注册
    Django-auth模块
    Django-csrf中间件
    基于django中settings中间件源码思想,实现功能的插拔式设计
    Django之中间件
    Django之cookie与session
    java中public与private还有protect的区别
  • 原文地址:https://www.cnblogs.com/yancea/p/7510679.html
Copyright © 2011-2022 走看看