LeetCode_167. Two Sum II - Input array is sorted
2024-10-06 07:43:28
167. Two Sum II - Input array is sorted
Easy
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.
package leetcode.easy; public class TwoSumIIInputArrayIsSorted {
@org.junit.Test
public void test() {
int[] numbers = { 2, 7, 11, 15 };
int target = 9;
System.out.println(twoSum(numbers, target));
} public int[] twoSum(int[] numbers, int target) {
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] == target) {
return new int[] { i + 1, j + 1 };
}
}
}
return new int[] { 0, 0 };
}
}
最新文章
- Oracle数据库备份、恢复及常见问题
- iOS版本更新的App提交审核发布流程
- 微软Face API体验——人脸检测
- app 支付宝 支付 alipaySdk
- PHP数组处理函数的使用array_push(一)
- HDU 5762
- KVC笔记
- Java_获取当前月最后一天
- Sql Server 常用方法、存储过程备用
- jstl标签库基础教程及其使用代码(一)。
- 为什么在我眼里你是一只傻逼——傻逼“常所用”句型之(2)——“当当网的就有XXX人评论,YYY%的推荐”
- oracle 生成随机数【待整理】
- python操作redis-过期时间
- JavaScript检测原始值、引用值、属性
- 树后台数据存储(採用webmethod)
- A Game of Thrones(19) - Jon
- Webserver管理系列:3、Windows Update
- hdu 2197 求长度为n的本原串 (快速幂+map)
- FreeCodeCamp----Intermediate Algorithm Scripting解法
- (转) argparse — 解析命令参数和选项