https://www.lanqiao.cn/problems/252/learning/
题目描述
给定一个数组,找到两个总和为特定值的索引。
例如给定数组 [1, 2, 3, -2, 5, 7],给定总和 7,则返回索引 [1, 4]。
若有多组符合情况则输出索引对中小索引最小的一组。
输入描述
第一行为给定数组的长度,不超过 100。
第二行为数组元素,元素大小不超过 100(可能为负数)。
第三行为特定值。
输出描述
输出一行,为两个索引值,升序输出。
输入输出样例
示例
输入
6
1 2 3 -2 5 7
7
输出
1 4
暴力
- public class Main {
- static int N=120;
- static int a[]=new int[N];
-
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int n=sc.nextInt();
- for(int i=0;i
- a[i]=sc.nextInt();
- }
- int target=sc.nextInt();
- for(int i=0;i
- for(int j=i+1;j
- if(a[i]+a[j]==target) {
- System.out.print(i+" "+j);
- return ;
- }
- }
- }
- }
- }
哈希
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Scanner;
-
- public class Main {
- static int N=110;
- static int a[]=new int[N];
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int n=sc.nextInt();
- HashMap
Map = new HashMap<>(); - for(int i=0;i
- a[i]=sc.nextInt();
- Map.put(a[i],i);
- }
- int target=sc.nextInt();
- for(int i=0;i
- int A=a[i];
- if(Map.containsKey(target-a[i])) {
- System.out.println(i+" "+Map.get(target-a[i]));
- break;
- }
- }
- }
- }
-
相关阅读:
09-JVM垃圾收集底层算法实现
C语言学习-数组(4)
VoLTE端到端业务详解 | S1AP协议
基于Python的世界各个国家的幸福度的公开数据集的数据挖掘
Scala 05 —— 函数式编程底层逻辑
列表元素
哪些重生奇迹mu地图适合刷玛雅宝石?
深入了解面向对象——面向对象的重要特征(C#)未写完
进程和线程
推理还是背诵?通过反事实任务探索语言模型的能力和局限性
-
原文地址:https://blog.csdn.net/qq_58631644/article/details/128028634