LeetCode 数组:两数之和2 - 输入数组有序
- 如果评论区没有及时回复,欢迎来公众号:ByteCode 咨询
- 公众号:ByteCode。致力于分享最新技术原创文章,涉及 Kotlin、Jetpack、算法、译文、系统源码相关的文章
题目来源于 LeetCode 上第 167号(Two Sum II - Input array is sorted)问题:两数之和2 - 输入数组有序。题目难度为 Easy。
英文地址:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
中文地址:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
题目描述
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.
示例:
Input: numbers = [2,7,11,15], target = 9 |
思路一:左右指针法
初始化左指针low指向数组起始位置,右指针height指向数组结束位置,时间复杂度o(n)
- 如果numbers[low] 和 numbers[height]的和sum等于target,返回low+,height+1
- 如果numbers[low] 和 numbers[height]的和sum小于target,则low++
- 如果numbers[low] 和 numbers[height]的和sum大于target,则height–
Java实现
public class Solution { |
Kotlin实现
class Solution { |
思路二:二分法查找
题目可知找两个数之和 a+b = taget,循环数组每一个元素a, 从剩余的元素里面用二分法查找另外一个元素 b= taget-a 即可,时间复杂度为o(nlogn)
- 循环每个元素a
- 从剩余元素用二分法查找元素b = taget-a,返回索引idnex,
- 如果index ==-1 ,则无结果返回,如果index!=-1,则直接返回a+1,index+1
Java实现
public class Solution { |
kotlin 实现
class Solution { |
- 本文作者:hi-dhl
- 本文标题:LeetCode 数组:两数之和2 - 输入数组有序
- 本文链接:https://hi-dhl.com/backup/LeetCode/arrays/01-two-sum-ii-input-array-is-sorted.html
- 版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 hi-dhl