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;
- }
- }
- }
- }
-
相关阅读:
Ajax之基本语法
java项目开发实例基于javaweb+mysql数据库实现的宠物领养|流浪猫狗网站含论文+开题报告
【MySQL】为什么使用B+树做索引
selenium查找网页如何处理网站资源一直加载非常卡或者失败的情况
《C++设计模式》——行为型
杰发科技AC7801 —— __attribute__指定地址存储常量
ABC212
MySql 中 select 使用
什么是作业指导书sop?sop作业指导书是什么意思?
tensorflow 里面的占位符 placeholder
-
原文地址:https://blog.csdn.net/qq_58631644/article/details/128028634