【力扣】167. 两数之和 II - 输入有序数组
发布日期:2021-06-29 19:44:11
浏览次数:3
分类:技术文章
本文共 1282 字,大约阅读时间需要 4 分钟。
题目:给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。说明:
返回的下标值(index1 和 index2)不是从零开始的。你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2] 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。class Solution { public int[] twoSum(int[] numbers, int target) { int index1, index2; for(index1 = 0; index1 < numbers.length - 1; index1++){ for(index2 = index1 + 1; index2 < numbers.length; index2++){ if(numbers[index1] + numbers[index2] == target){ int[] number = new int[]{ index1 + 1, index2 + 1}; return number; } } } return null; }}
优化后
class Solution { public int[] twoSum(int[] numbers, int target) { int index1 = 0, index2 = numbers.length - 1; while(index1 < index2){ if(numbers[index1] + numbers[index2] == target){ int[] number = new int[]{ index1 + 1, index2 + 1}; return number; } else if(numbers[index1] + numbers[index2] > target) index2--; else if(numbers[index1] + numbers[index2] < target) index1++; } return null; }}
转载地址:https://darkness.blog.csdn.net/article/details/104083468 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
感谢大佬
[***.8.128.20]2024年04月07日 02时14分24秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
C#获取微信公众号的access_token
2019-04-30
xls中分离超链接的文本和链接
2019-04-30
vba遍历指定的文件夹
2019-04-30
NPOI遍历excel表格
2019-04-30
sqlserver建立连接服务器
2019-04-30
Content-Security-Policy
2019-04-30
apple-mobile-web-app-capable
2019-04-30
C# byte换算
2019-04-30
tsql字符串截取
2019-04-30
C#中的abstract、virtual、interface关键字
2019-04-30
.Net面试题
2019-04-30
ABS
2019-04-30
c# List<string>和List<int>互相转换
2019-04-30
C#分页的总页数算法
2019-04-30
sqlserver 表连接更新字段
2019-04-30
jquery.formatDateTime
2019-04-30
jquery disabled
2019-04-30
同一个项目中使用MVC控制器和WebAPI控制器
2019-04-30