zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】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.

    Note:

    • 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.

    Example:

    Input: numbers = [2,7,11,15], target = 9
    Output: [1,2]
    Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

    思路

      在题中给出了数组是有序的,这个题比之前做过的两数之和还要简单。方法一就是需要使用辅助字典,我们先将数组遍历存储在字典中,键为元素值,值为下标位置。然后从数组第一个位置开始遍历,利用target值减去当前元素查找是否在字典中,直到遍历到最后一个元素结束。还有一个是这种办法的优化思想就是在将数组存进字典的过程中边存储边遍历查找。这样大部分情况下不用将数组全部存进字典中就可以找到结果。时间复杂度为O(n),空间复杂度为O(n)。第二种办法就是因为我们使用的是有序数组,我们可以设置两个指针一个指向头,一个指向尾部,然后每次根据与target的大小关系移动指针的位置。直到找到满足条件位置。时间复杂度为O(n),空间复杂度为O(1)。
    解决代码

    
    
     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         if not numbers:
     9             return []
    10         start, end = 0, len(numbers)-1      # 头尾指针
    11         while start < end:                  # 循环结束条件
    12             tem = numbers[start] + numbers[end]      
    13             if tem > target:       # 如果两指针处的和大于target,则将尾部指针向前移动一位。
    14                 end -= 1
    15             elif tem < target:    # 小于target时,向前移动start。
    16                 start += 1
    17             else:
    18                 return [start+1, end+1]  # 找到满足条件的数,直接返回
  • 相关阅读:
    iOS APP程序启动原理
    关于组合式继承和寄生式继承的个人理解
    servlet session 相关
    hadoop配置远程客户端
    将普通工程转为mvn标准工程(main resources)
    log4j2 配置文件
    mvn生成runnablejar 的方法
    普通工程转为mvn工程
    java ReentrantLock可重入锁功能
    在mapreduce中做分布式缓存的问题
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10993605.html
Copyright © 2011-2022 走看看