英文题目
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
题目解读:
- 给定一个整数数组,并给定一个特定的数;
- 寻找数组中和为该特定数的两个数,并输出其索引值;
程序代码:
import java.util.Scanner;
public class solution1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入即将输入的数组长度");
int c = sc.nextInt(); //定义一个整数代表输入数组长度
System.out.println("请输入数组");
int[] b = new int[c]; //定义长度为 5的数组
for(int i=0;i<c;i++){
b[i] = sc.nextInt();
}
System.out.println("请输入目标求和数");
int d = sc.nextInt();; //定义一个长度代表求和目标数
int []a=new int[2];
for(int k=0;k<c;k++) {
for(int j=k+1;j<c;j++) {
if(b[k]+b[j]==d){
a[0]=k;
a[1]=j;
for(int aa:a){
System.out.print(aa);//对数组进行输出
System.out.print("\t");
}
System.out.print("\n");
}
}
}
}
}
- 利用Scanner类实现从键盘读取数据;
- 可以输出所有满足条件的组合。
运行展示: