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