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 = [,,,], target =
Output: [,]
Explanation: The sum of and is . Therefore index1 = , index2 = .

题目描述,给定一个已排序的数组,和一个目标值,计算数组中的两个值的和等于目标值时的位置,这里位置不从0开始。

思路: 数组是以排序的,则使用两个指针,分别指向数组的头尾,当两数相加小于目标值是则头指针递增一位,当相加大于目标值值,尾指针递减。

下面是代码,感觉还有优化的地方。先贴出来。

public int[] TwoSum(int[] numbers, int target)
{
int[] result = new int[];
int lo=, hi=numbers.Length-;
while(lo < hi)
{
if (numbers[lo] + numbers[hi] < target) lo++;
else if (numbers[lo] + numbers[hi] > target) hi--;
else
break;
}
result[] = lo + ;
result[] = hi + ;
return result;
}

最新文章

  1. PHP的后期静态绑定
  2. 谈谈JavaScript MVC模式
  3. ABAP 特殊透明表
  4. 【Construct Binary Tree from Inorder and Postorder Traversal】cpp
  5. js 判断输入是否为正整数
  6. Eliza Doolittle lyrics Big City
  7. CDN-内容推送网络
  8. Android开发:Translucent System Bar 的最佳实践
  9. Char* ,CString ,WCHAR*之间的转换
  10. 我的Java笔记
  11. SparkMLlib学习分类算法之逻辑回归算法
  12. 狙杀ES6之开光篇
  13. android自定义文本框,后面带清空按钮
  14. [BZOJ]1177: [Apio2009]Oil
  15. 公司外网测试服务器 redis 被攻击复盘
  16. 《Tensorflow从入门到精通》
  17. 设计模式C++学习笔记之二(Proxy代理模式)
  18. @RequestBody注解的参数仅仅读取一次的问题解决。
  19. c/c++ 读入一行不确定个数的整数
  20. TOP100summit2017:豆瓣耿新跃---站在公司整体目标下看技术管理

热门文章

  1. Java面试宝典(7)混合2
  2. JavaScript常用技巧之进制转换
  3. reduce 好东西
  4. Cascade R-CNN目标检测
  5. Shell及其操作环境
  6. shell 逐行比较两个文件的内容是否一样(行数相同)
  7. 【原理】Reids字典
  8. jdbc 事物
  9. 数组转xls格式的excel文件&amp;数据转csv格式的excle
  10. win7 SP1 64位 原版 百度网盘下载