Java每日练习20190515

英文题目

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].

题目解读:

  1. 给定一个整数数组,并给定一个特定的数;
  2. 寻找数组中和为该特定数的两个数,并输出其索引值;

程序代码:

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类实现从键盘读取数据;
  • 可以输出所有满足条件的组合。

运行展示: 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

就是二二二二婷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值