【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[]{};
}
}

最新文章

  1. [LeetCode] UTF-8 Validation 编码验证
  2. 原生JS实现MVVM模式
  3. Centos下安装nginx rpm包
  4. 非正常关闭myeclicps后,出现错误Errors occurred during the build.的解决方法
  5. [Swift]基础
  6. knockout之入门介绍
  7. 使用Unity制作游戏关卡的教程(一)
  8. BZOJ 3680 吊打XXX
  9. ios属性和成员变量写在.h文件和.m文件中 区别?
  10. DHCP协议
  11. Spring 代理对象,cglib,jdk的问题思考,AOP 配置注解拦截 的一些问题.为什么不要注解在接口,以及抽象方法.
  12. Mac环境svn的使用
  13. elbow 求拐点
  14. elasticsearch template
  15. 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? 解决办法
  16. div配景图片全div显示
  17. 吴裕雄 实战PYTHON编程(8)
  18. 旋转链表(所有元素往右移) rotate list
  19. hoj Counting the algorithms
  20. 【OCP-052】052最新考试题库分析整理-第7题

热门文章

  1. 【C++】string::substr函数
  2. 利用hash或history实现单页面路由
  3. JS&#160;DOM(文档对象模型)与BOM(浏览器对象模型)
  4. Compatibility模式安装windows7后改为AHCI模式无法启动Windows7的解决办法
  5. 洛谷 P5367 【模板】康托展开(数论,树状数组)
  6. webgl(three.js)实现室内定位,楼宇bim、实时定位三维可视化解决方案
  7. 如何在GitHub上上传自己本地的项目?(很适合新手使用哦!)
  8. ASP.NET Core[源码分析篇] - WebHost
  9. Nacos(三):Nacos与OpenFeign的对接使用
  10. 初学HTML5做的小知识点