Post

ArraySort_같은 숫자 있는지 중복 확인하기

✅ Arrays.sort

배열 안에 같은 숫자가 있는지 없는지 확인하세요
있으면 “D” 출력
없으면 “U” 출력

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Main {

    public String solution(int size, int[] input){
        String answer= "U";
        Arrays.sort(input); //오름차순 정렬
        for(int i=1; i<size; i++){
            if(input[i]==input[i-1]) answer= "D"; //서로 이웃한 숫자들끼리 비교
        }
        return answer;
    }
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        int size= sc.nextInt();
        int[] input= new int[size];
        for(int i=0; i<size; i++){
            input[i]= sc.nextInt();
        }
        System.out.println(T.solution(size, input));
    }
}
//⭐️input:
8
20 25 52 30 39 33 43 33
//⭐️output:
D

🔵 ThingsILearned

✔️ Arrays.sort를 하면 오름차순으로 정렬해준다.

  1. 오름차순으로 배열을 정렬하면 다음과 같다.
  2. 20 25 30 33 33 39 43 52
  3. 따라서 옆에 있는 숫자들끼리만(이웃한 숫자들) 비교하면 됨

🟢 HashMapm으로 풀기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Main {

    public String solution(int size, int[] input){
        String answer= "U";
        HashMap<Integer, Integer> hashMap= new HashMap<>();
        for(int x: input){
            hashMap.put(x, hashMap.getOrDefault(x, 0)+1);
        }
        for(int x: hashMap.keySet()){
            if(hashMap.get(x) !=1) answer= "D";
        }
        return answer;
    }
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        int size= sc.nextInt();
        int[] input= new int[size];
        for(int i=0; i<size; i++){
            input[i]= sc.nextInt();
        }
        System.out.println(T.solution(size, input));
    }
}
  1. HashMapkey, value 저장
  2. 만약 중복된 숫자가 있었으면 value가 2 이상인 key가 있을 것
  3. 따라서 value가 2 이상인 key가 있는지 확인해서 있으면 answer= "D";

🔴 정답은 나오지만 time limit exceed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Main {

    public String solution(int size, int[] input){
        String answer= "U";
        for(int i=0; i<size; i++){
            for(int j=i+1; j<size; j++){
                if(input[i]==input[j]) answer= "D";
            }
        }
        return answer;
    }
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        int size= sc.nextInt();
        int[] input= new int[size];
        for(int i=0; i<size; i++){
            input[i]= sc.nextInt();
        }
        System.out.println(T.solution(size, input));
    }
}
This post is licensed under CC BY 4.0 by the author.