본문 바로가기
알고리즘/[백준] JAVA

[백준] 3052 나머지

by 코딩맛집 2023. 5. 2.

https://www.acmicpc.net/problem/3052

 

3052번: 나머지

각 수를 42로 나눈 나머지는 39, 40, 41, 0, 1, 2, 40, 41, 0, 1이다. 서로 다른 값은 6개가 있다.

www.acmicpc.net

 

방법1

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;

public class Main {
    public static void main(String[] args) throws IOException {

        HashSet<Integer> set = new HashSet<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        for(int i = 0; i<10; i++){
            set.add(Integer.parseInt(br.readLine()) % 42);
        }
        System.out.println(set.stream().count());
    }
}

 

Set 자료형의 특징

1. 중복을 허용하지 않는다.

2. 순서가 없다.

 

Set 자료형의 종류

  •  HashSet - 순서가 없다.
  •  TreeSet : 오름차순으로 값을 정렬하여 저장하는 특징이 있다.
  •  LinkedHashSet - 입력한 순서대로 값을 정렬하여 저장하는 특징이 있다.

등의 Set 인터페이스를 구현한 자료형이 있다.

 

Set 자료형의 메소드

  •  교집합 : retainAll()  
  •  합집합 : addAll()
  •  차집합 : removeAll()
  •  값 추가 : add()
  •  값 여러 개 추가 : addAll()
  •  특정 값 제거 : remove()

 

예시

s1을 기준으로

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;

public class Main {
    public static void main(String[] args){
        HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1,2,3,4,5));
        HashSet<Integer> s2 = new HashSet<>(Arrays.asList(3,4,5,6,7));

        HashSet<Integer> interaction = new HashSet<>(s1);
        interaction.retainAll(s2); //교집합
        System.out.println(interaction);

        HashSet<Integer> unionAll = new HashSet<>(s1);
        unionAll.addAll(s2); //합집합
        System.out.println(unionAll);

        HashSet<Integer> substract = new HashSet<>(s1);
        substract.removeAll(s2); //차집합
        System.out.println(substract);
    }
}

'알고리즘 > [백준] JAVA' 카테고리의 다른 글

[백준] 27866 문자와 문자열  (0) 2023.05.02
[백준] 10811 바구니 뒤집기  (0) 2023.05.02
[백준] 10813 공 바꾸기  (0) 2023.04.28
[백준] 2562 최댓값  (0) 2023.04.28
[백준] 10818 최소, 최대  (0) 2023.04.25