No sweet without sweat

[백준 1181 / 자바(JAVA)] - 단어 정렬 본문

백준

[백준 1181 / 자바(JAVA)] - 단어 정렬

Remi 2023. 5. 2. 23:26
728x90
반응형

     

문제의 Key

 

1. TreeSet O(log n)
- null 입력은 가능하지만 한 번만 저장 가능하고 중복X
- 오름차순으로 데이터를 정렬합니다.
- 내부적으로 TreeMap을 사용
        

성능 차이 비교

: HashSet > LinkedHashSet > TreeSet

  ★ Hashset은 stream.sort을 지양하자.
- Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed.
- The Streams API can convert an ordered stream, which may represent an ordered data source such as a list or a sorted set, into an unordered stream.
-  We can also convert an unordered stream into an ordered stream by applying an sorting intermediate operation.

   

 

 

 

package 백준.정렬;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Stream;

/*
* 메모리 :26028 KB
* 시간 : 860ms
* */
public class 단어정렬_1181 {
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int num = Integer.parseInt(br.readLine());

        String[] arr = new String[num];

        TreeSet<String> treeSet = new TreeSet<>();

        for (int i = 0; i < num; i++) {
            treeSet.add(br.readLine());
        }

        Object[] arr2 = treeSet.stream().sorted(Comparator.comparingInt(String::length)).toArray();
//                .forEach(System.out::println)
        for(Object arrrr : arr2){
            System.out.println(arrrr);
        }

/*

        TreeSet O(log n)
        - null 입력은 가능하지만 한 번만 저장 가능하고 중복될 수 없습니다.
        - 객체(데이터)를 중복 저장할 수 없지만 오름차순으로 데이터를 정렬합니다.
        - 내부적으로 TreeMap을 사용합니다.
        HashSet > LinkedHashSet > TreeSet 순서로 성능의 차이

        Hashset은 stream.sort을 지양하자.

        Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed.

        The Streams API can convert an ordered stream, which may represent an ordered data source such as a list or a sorted set, into an unordered stream.

        We can also convert an unordered stream into an ordered stream by applying an sorting intermediate operation.

        */
    }
}

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

 

1181번: 단어 정렬

첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

www.acmicpc.net

 

 

728x90
반응형
Comments