https://www.hackerrank.com/challenges/big-sorting/problem?isFullScreen=true 

 

Big Sorting | HackerRank

Sort an array of very long numeric strings.

www.hackerrank.com

 

기존 풀이 방법

  • String -> int 
  • int -> String 하는 과정에서 시간초과로 실패 
    public static List<String> bigSorting(List<String> unsorted) {
        List<BigInteger> sorted = unsorted.stream()
                .map(BigInteger::new).sorted().collect(Collectors.toList());
        Collections.sort(sorted);
        List<String> answer = sorted.stream()
                .map(String::valueOf)
                .collect(Collectors.toList());
        return answer;
    }

 

새로운 풀이 방법

  • compareTo를 통해서 자릿수를 비교해가면서 오름차순 정렬
    public static List<String> bigSorting(List<String> unsorted) {
        Collections.sort(unsorted, (x, y) -> {
            if(x.length() == y.length()){
                return x.compareTo(y);
            } else {
                return x.length() - y.length();
            }
        });
        return unsorted;
    }

+ Recent posts