By GokiSoft.com|
14:08 14/07/2023|
Java Advanced
[Share Code] Tìm mảng a2 kết hợp mảng a1 tạo mảng a là các phân tử liên tiếp nhau - C2209I
Tìm mảng a2 kết hợp mảng a1 tạo mảng a là các phân tử liên tiếp nhau
#BT1230.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.gokisoft.java2.lesson03;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
/**
*
* @author teacher
*/
public class BT1230 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> a1 = new ArrayList<>();
ArrayList<Integer> a2 = new ArrayList<>();
// ArrayList<Integer> a = new ArrayList<>();
System.out.println("Nhap so phan tu trong mang a1: ");
int n = Integer.parseInt(scan.nextLine());
System.out.println("Nhap cac phan tu trong mang a1: ");
for (int i = 0; i < n; i++) {
System.out.println("Phan tu "+(i+1)+": ");
a1.add(Integer.valueOf(scan.nextLine()));
}
//a1: 6, 2, 4, 8 -> 2, 3, 6, 8
//a2: 4, 5, 7
System.out.println("Tim mang a2?");
//B1. Sap xep mang a1: 2, 3, 6, 8
//Giai thuat:
// i: 0 -> a1.length - 2 = 0 -> 2 (0, 1, 2)
// i = 0: v0 = 2 -> v1 = 3 => Kiem tra giua 2 phan tu nay co gia tri nao ko
// i = 1: v1 = 3 -> v2 = 6 => 4, 5
// i = 2: v2 = 6 -> v3 = 8 => 7
Collections.sort(a1);//a1: 0 -> a1: length - 1
for (int i = 0; i < a1.size() - 1; i++) {
// a.add(a1.get(i));
for (int j = a1.get(i) + 1; j < a1.get(i + 1); j++) {
a2.add(j);
// a.add(j);
}
}
// a.add(a1.get(a1.size() - 1));
for (Integer v : a2) {
System.out.println(v);
}
// System.out.println("Mang sau khi ket hop: ");
// for (Integer v : a) {
// System.out.println(v);
// }
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)