LeetCode 167 Two Sum II - Input array is sorted (两点法)
来源:互联网 发布:万象域名 编辑:程序博客网 时间:2024/06/07 05:44
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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
题目链接:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
题目分析:因为数组有序,因此可以使用两点法,一指针在开头,一指针在结尾,若相加小于target,则开头指针后移,大于则结尾指针前移,相等就break
public class Solution { public int[] twoSum(int[] numbers, int target) { int[] ans = new int[2]; int sz = numbers.length; int l = 0, r = sz - 1; while (l < r) { if (numbers[l] + numbers[r] < target) { l ++; } else if (numbers[l] + numbers[r] > target) { r --; } else { ans[0] = l + 1; ans[1] = r + 1; break; } } return ans; }}
0 0
- LeetCode 167 Two Sum II - Input array is sorted (两点法)
- leetcode 167: Two Sum II - Input array is sorted
- Leetcode NO.167 Two Sum II - Input array is sorted
- [leetcode 167] Two Sum II - Input array is sorted
- LeetCode 167: Two Sum II - Input array is sorted
- leetcode 167 Two Sum II - Input array is sorted C++
- LeetCode 167 Two Sum II - Input array is sorted
- LeetCode #167: Two Sum II - Input array is sorted
- LeetCode 167:Two Sum II - Input array is sorted
- LeetCode[167] Two Sum II - Input array is sorted
- Leetcode #167 Two Sum II - Input array is sorted
- Leetcode 167 Two Sum II - Input array is sorted
- leetcode 167 Two Sum II - Input array is sorted
- [LeetCode]167 Two Sum II - Input array is sorted
- LeetCode-Two Sum II - Input array is sorted
- [Leetcode]Two Sum II - Input array is sorted
- leetcode--Two Sum II - Input array is sorted
- LeetCode 题解(274) : Two Sum II - Input array is sorted
- vue.js 计算属性$watch
- 图文结合
- Yii2.0增删改查
- Pointers on C 重点笔记 第三章
- VC_GPIB_Demo
- LeetCode 167 Two Sum II - Input array is sorted (两点法)
- 1069. The Black Hole of Numbers
- 判断一个数字是否为质数。
- eclipse使用mybatis做查询时条件有汉字的不能执行成功
- 树莓系统安装+网络(杂记)
- 设计模式第一天 策略模式
- bzoj1222 [HNOI2001]产品加工
- Leetcode刷题记——24. Swap Nodes in Pairs(交换成对结点)
- iOS label文字添加中划线和下划线