[Coding Test | Programmers] - the largest number (Java)

종글·2024년 9월 21일

algorithm

목록 보기
6/6
post-thumbnail

Approach

If you want to compare each number with an integer operation, convert it into a string and compare it because the operation gets longer

This problem is a griddy problem, but it seems to be a problem that used sorting as a griddy solution. As soon as you sort by furnace sorting, you find a larger number.

Algorithm & Data Structure

Sort

Time Complexity

O((n-k) * K)

Code

import java.util.*;
class Solution {
    public String solution(int[] numbers) {
        String answer = "";
        //String 비교를 위해 String 으로 변환
        String[] nums = Arrays.stream(numbers)
                              .mapToObj(String::valueOf)
                              .toArray(String[]::new);
        
        //두 수를 붙인 숫자중 큰수를 앞에 리턴
        Arrays.sort(nums, (x,y) -> (y+x).compareTo(x+y));
        
        answer = String.join("", nums);
        
         if (answer.startsWith("0")) {
            return "0";
        }
        return answer;
    }
  
}
profile
기록되지 않은 앎은 단지 들음에 지나지 않는다

0개의 댓글