博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
167. Two Sum II - Input array is sorted
阅读量:7231 次
发布时间:2019-06-29

本文共 2201 字,大约阅读时间需要 7 分钟。

题目:

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

链接: 

题解:

排序好的数组求two sum。用头尾两个指针对着夹逼一下就可以了。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {    public int[] twoSum(int[] numbers, int target) {        int[] res = {-1, -1};        if(numbers == null || numbers.length == 0)            return res;        int lo = 0, hi = numbers.length - 1;                while(lo < hi) {            if(numbers[lo] + numbers[hi] < target)                lo++;            else if(numbers[lo] + numbers[hi] > target)                hi--;            else {                res[0] = lo + 1;                res[1] = hi + 1;                return res;            }        }                return res;    }}

 

二刷:

和一刷一样,双指针夹逼

Java:

public class Solution {    public int[] twoSum(int[] numbers, int target) {        int[] res = {-1, -1};        if (numbers == null || numbers.length == 0) {            return res;        }        int lo = 0, hi = numbers.length - 1;        while (lo <= hi) {            int sum = numbers[lo] + numbers[hi];            if (sum < target) {                lo++;            } else if (sum > target) {                hi--;            } else {                res[0] = lo + 1;                res[1] = hi + 1;                return res;            }        }        return res;    }}

 

三刷:

Java:

public class Solution {    public int[] twoSum(int[] nums, int target) {        if (nums == null || nums.length < 2) return nums;        int lo = 0, hi = nums.length - 1;        while (lo < hi) {            int sum = nums[lo] + nums[hi];            if (sum == target) return new int[] {lo + 1, hi + 1};            else if (sum < target) lo++;            else if (sum > target) hi--;        }        return new int[] {-1, -1};    }}

 

 

 

Reference:

转载地址:http://cmpfm.baihongyu.com/

你可能感兴趣的文章
Weui 文件上传完整版示例
查看>>
ubuntu上安装 MySQL 启动/停止 连接MySQL
查看>>
liunx 修改ssh 端口22
查看>>
iOS企业证书申请介绍
查看>>
hdu 1950 Bridging signals(最长上升子序列)
查看>>
jquery学习收获
查看>>
es6js promise在ie中报错“未定义”
查看>>
思科HSRP和Port-channel配置
查看>>
常用的sql脚本(陆续更新)
查看>>
mongodb的gridfs
查看>>
api图片传输,转成64位字符串进行传输
查看>>
Matlab高斯分布输入的PID控制
查看>>
【Java】自定义异常
查看>>
Ubuntu14.04server开放rootssh登录权限
查看>>
错误 1 error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
查看>>
Linux 权限基础说明
查看>>
2017级面向对象程序设计寒假作业3
查看>>
迭代器
查看>>
Linux OpenCV 静态链接错误
查看>>
Java多线程&集合类-详细版
查看>>