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

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

Q: 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

 

 

1 public class Solution2{ 2  3 // O(n) runtime, O(n) space; 4  5 // We have two pointers, start and end,  6  7 // firstly, we add start and end, because the array is sorted in ascending order, 8  9 //if the sum is smaller than our target, we just increase the start point;10 11 // if the sum is greater than our target, we just decrease the end point,12 13 //keep doing this, until the sum is equal to our target.14 15   public int[] twoSum(int[] numbers, int target) {16 17     int i = 0, j = numbers.length - 1;18 19     while(i < j){20     if(numbers[i] + numbers[j] < target){21       i++;22     } else if(numbers[i] + numbers[j] > target){23       j--;24      } else {25        return new int[] {i+1, j+1};26     }27 28           }29    throw new IllegalArgumentException("No two sum solution");30   }31 32 }

 

转载于:https://www.cnblogs.com/caomeibaobaoguai/p/4873386.html

你可能感兴趣的文章
SQL Server sp_configure 控制内存使用
查看>>
通读《构建之法》提出问题
查看>>
VB生成xml
查看>>
左值、左值引用、右值、右值引用
查看>>
中转注入
查看>>
ACM 算法目录
查看>>
android 读取SD卡文件
查看>>
Flatten Binary Tree to Linked List
查看>>
Spring(十二)使用Spring的xml文件配置方式实现AOP
查看>>
开源 java CMS - FreeCMS2.3会员个人资料
查看>>
smack 4.1.2+openfire 3.10.2i
查看>>
sqlserver 中EXEC和sp_executesql使用介绍
查看>>
Javascript- Javascript学习
查看>>
day 5.基本数据类型:字典(dict)
查看>>
python 机器学习之岭回归
查看>>
Centos7通过Docker安装Sentry(哨兵)
查看>>
加入收藏兼容ie和火狐
查看>>
Linux常用的网络命令
查看>>
树莓派蓝牙连接
查看>>
Android 网络编程
查看>>