STEP: 13 集合の探索
問題
解答
step13.java
import java.util.*;
public class Main {
private static final String YES = "Yes";
private static final String NO = "No";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int b = sc.nextInt();
String result = NO;
for(int i = 0; i < n; i++){
if(b == sc.nextInt()){
result = YES;
break;
}
}
System.out.println(result);
}
}
結果
STEP: 14 重複の削除
問題
解答
step14java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < n; i++){
int number = sc.nextInt();
if(!list.contains(number)){
list.add(number);
}
}
for(int i = 0; i < list.size(); i++){
if(i<list.size()-1){
System.out.print(list.get(i) + " ");
} else{
System.out.print(list.get(i));
}
}
}
}
結果
STEP: 15 重複の判定 1
問題
解答
step15.java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// 1回目の要素は、探索対象外の為、要素を先にリストに入れる
list.add(sc.nextInt());
// 要素が1つ減っているのでn-1とする
for(int i = 0; i < n-1; i++){
int number = sc.nextInt();
if(list.contains(number)){
System.out.println("Yes");
}else{
System.out.println("No");
list.add(number);
}
}
}
}
結果
STEP: 16 重複の判定 2
問題
解答
step16.java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Long> list = new ArrayList<Long>();
list.add(sc.nextLong());
for(int i = 0; i < n-1; i++){
Long number = sc.nextLong();
if(list.contains(number)){
System.out.println("Yes");
} else {
System.out.println("No");
list.add(number);
}
}
}
}
結果
FINAL問題 集合の結合
問題
解答
final.java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 0; i < n*2; i++){
int number = sc.nextInt();
if(!list.contains(number)){
list.add(number);
}
}
Collections.sort(list);
for(int i = 0; i < list.size(); i++){
if(i < list.size()-1){
System.out.print(list.get(i) + " ");
} else {
System.out.println(list.get(i));
}
}
}
}