公众号: 爱写bug(ID:icodebugs)

给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。

函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2

说明:

  • 返回的下标值(index1 和 index2)不是从零开始的。
  • 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。

示例:

输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。

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.

解题思路:

​ 双指针例题的加强版:一个指针从左向右移动,另一个指针从右向左,左指针与右指针之和如果小于 target ,则左指针右移一位,如果大于target ,右指针左移一位,直到双指针之和等于target。

代码(java):

class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
int i = 0, j = numbers.length - 1,temp;//i为左指针,j为右指针
while (i < j) {
temp=numbers[i] + numbers[j];//先记录两数之和
if (temp == target) {//等于目标数则记录其索引
res[0] = i + 1;
res[1] = j + 1;
return res;
} else if (temp < target) {//小于目标数,左指针右移一位
i++;
} else {//大于目标数,右指针左移一位
j--;
}
}
return null;
}
}

代码(python3):

class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
i=0
j=len(numbers)-1
while i<j:
if numbers[i]+numbers[j]==target:
return i+1,j+1
elif numbers[i]+numbers[j]>target:
j-=1
else:i+=1

总结:

这道题本身很简单,几个小细节:

  • if (temp == target) 先判断与目标数是否相同 可减少运行时间(因为Leetcode是拿很多不同数据来运行,而不是一条超长数据。仔细想想这里的区别)
  • temp=numbers[i] + numbers[j] 先把两数之和记录下来,像py3里那种判断两次(==、>)每次都计算一次两数和,会消耗更多时间,这在判断条件增多时会很明显。

扩展:

后面找到py3一种很有意思的解法,就是效率不高,扩展一下思路即可:

class Solution(object):
def twoSum(self, numbers, target):
s = {}
r = []
for i in range(len(numbers)):
if numbers[i] in s.keys():#判断该数在s键值对的键中是否存在。因为键值对的键记录的是差值
r.append(s[numbers[i]]+1)
r.append(i+1)
return r
s[target-numbers[i]] = i#目标数与每一个数差值记录为s键值对的键,其索引记录为值
return None

利用py3字典特性解题,很有意思。

LeetCode 167:两数之和 II - 输入有序数组 Two Sum II - Input array is sorted的更多相关文章

  1. [Swift]LeetCode167. 两数之和 II - 输入有序数组 | Two Sum II - Input array is sorted

    Given an array of integers that is already sorted in ascending order, find two numbers such that the ...

  2. 167两数之和II-输入有序数组

    from typing import List# 这道题很容易能够想到,只需要遍历两边列表就可以了# 两层循环class Solution: def twoSum(self, numbers: Lis ...

  3. LeetCode 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)

    653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定 ...

  4. Java实现 LeetCode 167 两数之和 II - 输入有序数组

    167. 两数之和 II - 输入有序数组 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index1 必 ...

  5. Java实现 LeetCode 653 两数之和 IV - 输入 BST(递归,找差值)

    653. 两数之和 IV - 输入 BST 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true. 案例 1: 输入: 5 / \ 3 6 / ...

  6. Leetcode 167. 两数之和 II - 输入有序数组 By Python

    给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2. 说明: 返回的下标值 ...

  7. LeetCode 167. 两数之和 II - 输入有序数组

    题目: 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值index1 和 index2,其中 index1 必须小于 index2. 说明: 返回的 ...

  8. LeetCode 167.两数之和(C++)

    给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2. 说明: 返回的下标值 ...

  9. LeetCode167.两数之和II-输入有序数组

    给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2. 说明: 返回的下标值 ...

随机推荐

  1. 动态ALV表实例-移动类型汇总

    TABLES:MSEG,MAKT. "定义结构 TYPES:BEGIN OF TY_DATA, MJAHR LIKE MSEG-MJAHR, "物料凭证的年份 MBLNR LIKE ...

  2. 基于OpenCV.Net投影法进行文本分块切割

    假设有如下一张图,如何把其中的文本分块切割出来,比如“华普超市朝阳门店”.“2015-07-26”就是两个文本块. 做图像切割有很多种方法,本文描述一种最直观的投影检测法.先来看看什么是投影,简单来说 ...

  3. JDK1.8新特性——Stream API

    JDK1.8新特性——Stream API 摘要:本文主要学习了JDK1.8的新特性中有关Stream API的使用. 部分内容来自以下博客: https://blog.csdn.net/icarus ...

  4. jQuery HTML/CSS 方法大全

    下表列出了用于操作HTML和CSS的所有方法. 方法 描述 addClass() 向所选元素添加一个或多个类名 after() 在所选元素之后插入内容 append() 在所选元素的末尾插入内容 ap ...

  5. Vue 拖拽组件 vuedraggable 和 vue-dragging

    一.描述 之前用 vue 写过一个在线的多二维码生成服务,体验地址:https://postbird.gitee.io/vue-online-qrcode/ 后面发现二维码多了之后有时候想要排序,需要 ...

  6. vuePress自动部署到Github Page脚本踩坑

    背景 照着官网的教程来就行了,踩了个小坑,记录一下,希望对你有帮助 这是部署后的效果 小坑1 如图所示,官网推荐部署命令 然而windows 没有bash 指令, 直接运行报错 两个解决方法: 项目根 ...

  7. ES6 入门系列 ArrayBuffer

    由来 推荐在这里阅读 js操作二进制数据三兄弟 ArrayBuffer对象, TypeArray视图和DataView视图 它们都以数组的语法处理二进制数据,所以统称为二进制数组 ::: tip 二进 ...

  8. jQuery-ready与load

      // ready 在DOM加载完成时运行的代码 $(document).ready(function(){ // 在这里写代码... }) // 可以简写为 $(function(){ // 在这 ...

  9. linux 环境下 apache tomcat 安装jenkins

    参考文档: https://blog.51cto.com/12629984/1980034 https://www.cnblogs.com/lxs1314/p/8567652.html https:/ ...

  10. 第14节_BLE协议ATT层

    下面这个图是BLE协议各层跟医院的各个科室的类比图: 跟医院类比,ATT层就是化验室,通过它可以得到各种检查结果──属性.这些检查结果之间有什么联系,它们组合起来体现了什么,化验室是不知道的,这些得由 ...