LeetCode-167:Two Sum II
来源:互联网 发布:最好的源码下载网站 编辑:程序博客网 时间:2024/05/22 17:04
Question
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.
Example
Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2
问题解析:
给定升序排序数组,找到两个和为给定数字的元素,返回二者位置。注意index1 < index2,且不使用重复元素。
Answer
Solution 1:
左右两指针相加靠近。
- 注意题目与
LeetCode-1:Two Sum
存在不同的地方,本题要求index1 < index2,可以使用除与LeetCode-1
相同的HashMap之外其他的方法。 - 题中要求index1 < index2,那么我们可以利用这样的性质,设置左右两个指针,从两端向中间逼近,每次都用两个数判断是否等于目标值,等于则返回,不等则判断大小,增减左右指针。
class Solution { public int[] twoSum(int[] numbers, int target) { int left = 0; int right = numbers.length-1; while (numbers[left] + numbers[right] != target){ if (numbers[left] + numbers[right] > target){ right--; }else{ left++; } } return new int[]{left+1, right+1}; }}
- 时间复杂度:O(n);空间复杂度:O(1)
阅读全文
0 0
- Leetcode #167 Two Sum II
- Leetcode 167 Two Sum II
- LeetCode 167 Two Sum II
- LeetCode[167]Two Sum II
- LeetCode-167:Two Sum II
- leetcode 167--- Two Sum II
- LeetCode #167 Two Sum II
- [leetcode] Two Sum II
- LeetCode : Two Sum II
- leetcode [Two Sum II
- 【LeetCode】Two Sum II
- 【leetcode】Two Sum II
- LeetCode:Two Sum II
- leetcode--Two Sum II
- leetcode Two Sum II
- leetcode -- Two Sum II
- leetCode-Two Sum II
- [Leetcode]1(167). Two Sum I, II
- iOS应用架构谈 开篇
- Stream流的操作案例
- 查找销售模块中装箱单提单主提单当前的编号
- Python3之Django Web框架安装mysqlclient
- 嵌入式linux路线图
- LeetCode-167:Two Sum II
- Hive安装
- 最大子段和
- 【安卓随笔】引入OpenCV进行NDK开发之图片传递(案例:文字水印)
- java图形图像处理库 Thumbnails
- JAVA基础学习20171024-初识
- LOMBOK使用记录
- NKOJ 4252 数三角形(乱搞)
- 2017NOIP模拟赛 软件安装(tarjan缩点+树形dp)