当前位置:网站首页>根据输入target,返回数组的两个下标。
根据输入target,返回数组的两个下标。
2022-07-28 14:31:00 【pshdhx_albert】
numbers = [2,7,11,15], target = 9 数组下标从1开始,返回 1 和2 【1,2】 输入:numbers = [2,3,4], target = 6 输出:[1,3] 输入:numbers = [-1,0], target = -1 输出:[1,2]
public class ReturnArrsEqualTarget {
public static int[] twoSum(int[] numbers, int target) {
/**
* 在数组中找到两个数,使得它们的和等于目标值,可以首先固定第一个数,然后寻找第二个数,
* 第二个数等于目标值减去第一个数的差。利用数组的有序性质,
* 可以通过二分查找的方法寻找第二个数。为了避免重复寻找,在寻找第二个数时,只在第一个数的右侧寻找。
*/
//固定第一个数字,查找第二个数字,第二个数字==target-第一个数字; 因为有序,所以可以利用二分法查找第二个数字
/*for(int i=0;i<numbers.length-1;i++){
for(int j=i+1;j<numbers.length;j++){
if(target == numbers[i]+numbers[j]){
return new int[]{i+1,j+1};
}
}
}*/
for (int i = 0; i < numbers.length; ++i) {
int low = i + 1, high = numbers.length - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
if (numbers[mid] == target - numbers[i]) {
return new int[]{i + 1, mid + 1};
} else if (numbers[mid] > target - numbers[i]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
}
return null;
}
public static void main(String[] args) {
int arr[] = {-1,0};
int[] ints = twoSum(arr, -1);
System.out.println(Arrays.toString(ints));
}
}
/**
* 凡是和:可以固定一个数字,去查找另一个数字,可以做加法,可以做减法。
* 凡是有序,查找数字或者是数字下标,可以利用二分法查找即可。
*/边栏推荐
- 2022-07-28日报:Science:AI设计蛋白质再获突破,可设计特定功能性蛋白质
- sql 开发篇一 之 表锁查询及解锁
- Installing CONDA and configuring Jupiter
- Encapsulate the unified return object messageresult
- 听说crmeb多商户增加了种草功能?
- sql语句的执行流程
- Grpc protocol buffer
- 流畅到让人头皮发麻的单商户商城,你用过吗?
- Share the HR experience of the first and second tier companies
- 腾讯面试之--请你设计一个实现线程池顺序执行
猜你喜欢
![[leetcode] 35. Search the insertion position](/img/cd/bd6f5152be098072b3a43a456e4c99.png)
[leetcode] 35. Search the insertion position

腾讯面试之--请你设计一个实现线程池顺序执行

MySQL 8.0 common (continuous update)

Shellcode writing learning environment

Daily question (retrospective)

Celery related

RY-D1/1电压继电器

Publish raspberry pie web page with cpolar (release of apache2 web page)

PMP【敏捷教材+全真模拟题】,续6月25日考试之后,敏捷就成为了重中

Hjs-de1/2 time relay
随机推荐
8、实时数据备份和实时时钟功能实现
How to set some app application icons on the iPhone Apple phone that you don't want others to see? How to hide the app application settings on the mobile desktop so that they can be used normally afte
4、主程序和累积中断处理例程实现代码
ERROR:bokeh.core.validation. check:E-1001 (BAD_COLUMN_NAME)
.net core 2.2 版本跨域配置
ECCV 2022 | SSP: 自支持匹配的小样本任务新思想
crmeb 标准版window+phpstudy8安装教程(二)
crmeb标准版4.4都会增加哪些功能
Write a standard character device driver with your hands
7、实时数据备份和实时时钟相关定义
GRC concept GRC architecture RPC lifecycle
MIT指出公开预训练模型不能乱用
DJ-131/60C电压继电器
Grpc frequently asked questions
Opencv - closely combine multiple irregular small graphs into large graphs
Apple iPhone app icon hidden how to retrieve and restore the hidden app icon displayed on the iPhone iPhone desktop to the iPhone iPhone iPhone desktop?
day 7/12
ArcGIS Pro 中的编辑器
Customer service system attached to crmeb Standard Edition
Shellcode writing learning environment