【LeetCode】Two Sum II - Input array is sorted
2024-09-01 06:23:33
【Description】
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.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
【AC code】
一、暴力法 时间复杂度:O(n^2)
class Solution {
public int[] twoSum(int[] numbers, int target) {
int arrlen = numbers.length;
for (int i = 0; i < arrlen - 1; i++) {
for (int j = i + 1; j < arrlen; j++) {
if (numbers[i] + numbers[j] == target) return new int[]{i + 1, j + 1};
}
}
return new int[]{};
}
}
二、二分查找法 时间复杂度:O(nlogn)
class Solution {
public int[] twoSum(int[] numbers, int target) {
int arrlen = numbers.length;
for (int i = 0; i < arrlen; i++) {
int left = i + 1, right = arrlen - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int tmp = numbers[i] + numbers[mid];
if (tmp > target) right = mid - 1;
else if (tmp < target) left = mid + 1;
else return new int[]{i + 1, mid + 1};
}
}
return new int[]{};
}
}
三、双索引法 时间复杂度:O(n)
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0, right = numbers.length - 1;
while (left < right) {
int tmp = numbers[left] + numbers[right];
if (tmp == target) return new int[]{left + 1, right + 1};
else if (tmp > target) right--;
else left++;
}
return new int[]{};
}
}
最新文章
- [LeetCode] UTF-8 Validation 编码验证
- 原生JS实现MVVM模式
- Centos下安装nginx rpm包
- 非正常关闭myeclicps后,出现错误Errors occurred during the build.的解决方法
- [Swift]基础
- knockout之入门介绍
- 使用Unity制作游戏关卡的教程(一)
- BZOJ 3680 吊打XXX
- ios属性和成员变量写在.h文件和.m文件中 区别?
- DHCP协议
- Spring 代理对象,cglib,jdk的问题思考,AOP 配置注解拦截 的一些问题.为什么不要注解在接口,以及抽象方法.
- Mac环境svn的使用
- elbow 求拐点
- elasticsearch template
- tensoflow模型中提示:ValueError: Variable rnn/basic_rnn_cell/kernel already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? 解决办法
- div配景图片全div显示
- 吴裕雄 实战PYTHON编程(8)
- 旋转链表(所有元素往右移) rotate list
- hoj Counting the algorithms
- 【OCP-052】052最新考试题库分析整理-第7题
热门文章
- 【C++】string::substr函数
- 利用hash或history实现单页面路由
- JS&#160;DOM(文档对象模型)与BOM(浏览器对象模型)
- Compatibility模式安装windows7后改为AHCI模式无法启动Windows7的解决办法
- 洛谷 P5367 【模板】康托展开(数论,树状数组)
- webgl(three.js)实现室内定位,楼宇bim、实时定位三维可视化解决方案
- 如何在GitHub上上传自己本地的项目?(很适合新手使用哦!)
- ASP.NET Core[源码分析篇] - WebHost
- Nacos(三):Nacos与OpenFeign的对接使用
- 初学HTML5做的小知识点