每天一算:Two Sum II
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
- 返回的下标值(index1 和 index2)不是从零开始的。
- 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9 输出: [1,2] 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
思路
初始化左指针left指向数组起始,初始化右指针right指向数组结尾。
根据已排序这个特性,
(1)如果numbers[left]与numbers[right]的和tmp小于target,说明应该增加tmp,因此left右移指向一个较大的值。
(2)如果tmp大于target,说明应该减小tmp,因此right左移指向一个较小的值。
(3)tmp等于target,则找到,返回left+1和right+1。(注意以1为起始下标)
动画演示
代码
// 对撞指针
// 时间复杂度: O(n)
// 空间复杂度: O(1)
class Solution {
public:vector<int> twoSum(vector<int>& numbers, int target) {int l = 0, r = numbers.size() - 1;while(l < r){if(numbers[l] + numbers[r] == target){int res[2] = {l+1, r+1};return vector<int>(res, res+2);}else if(numbers[l] + numbers[r] < target)l ++;else // numbers[l] + numbers[r] > targetr --;}}复制代码
欢迎关注
每天一算:Two Sum II相关推荐
- LeetCode 167. Two Sum II - Input array is sorted--Python解法
题目地址:Two Sum II - Input array is sorted - LeetCode Given an array of integers that is already sorted ...
- Digit Sum II( ABC044ARC060)
问题 G: Digit Sum II 时间限制: 1 Sec 内存限制: 128 MB 提交: 36 解决: 11 [提交][状态][讨论版][命题人:admin] 题目描述 For intege ...
- [LeetCode]113.Path Sum II
[题目] Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the giv ...
- Lintcode: k Sum II
Given n unique integers, number k (1<=k<=n) and target. Find all possible k integers where the ...
- LeetCode_Path Sum II
一.题目 Path Sum II Total Accepted: 46778 Total Submissions: 175830My Submissions Given a binary tree a ...
- 113. Path Sum II
/** 113. Path Sum II * 11.18 By Mingyang* 典型的backtracking,不过注意,这里的值可能是负数,所以不能用sum小于0来做任何判断* 1.长度标准:无 ...
- leetcode 112. Path Sum, 113. Path Sum II | 112,113. 路径总和 I, II(Java)
题目 https://leetcode.com/problems/path-sum/ https://leetcode.com/problems/path-sum-ii/ 题解 简单的遍历二叉树,不解 ...
- Leetcode: mimimum depth of tree, path sum, path sum II
思路: 简单搜索 总结: dfs 框架 1. 需要打印路径. 在 dfs 函数中假如 vector 变量, 不用 & 修饰的话就不需要 undo 2. 不需要打印路径, 可设置全局变量 ans ...
- LeetCode 113. Path Sum II
113. Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum eq ...
最新文章
- 为什么要打jar_生活在西北的兰州人过春节为什么要打太平鼓?
- Java总复习(一)
- 解决Android 插件化方法找不到 问题
- 横竖三个数的和相等_怎样证明 0.999… = 1?数值上是相等的,那么两者的区别是什么?...
- Delphi读写二进制文件
- 记一次mysql主从同步因断电产生的不能同步问题 1236 and 1032
- 决策树 Decision Tree
- LabelImg 图片标注工具 for Mac
- irr java_Java版的IRR(内部收益率)实现
- oracle 11g不能启动,[求助]oracle 11g无法启动
- 安装Altera USB-Blaster驱动程序遇到的问题
- SpringBoot工程接入第三方支付渠道支付宝(C扫B支付)
- 三星S7edge从8.0降到6.0.1,只为流畅的飞一般的感觉_我是亲民_新浪博客
- 苹果可穿戴设备项目背后的那些专家
- 目录操作的相关API 和 获取文件的属性信息
- Python详细介绍及使用(基础篇)
- 电脑重装系统后我的电脑图标怎么添加到桌面上显示
- 店铺信息html,编辑店铺信息.html
- 针对校园 移动 联通 路由器安装方法
- 00后大学生:无穷小微积分教材何在?