티스토리 뷰
leetcode.com/problems/largest-number/
Largest Number - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
주어진 숫자 리스트들을 이어붙였을 때 가장 큰 숫자를 찾으면 된다.
아이디어는 Sorting해서 큰 숫자 순으로 이어붙여주는건데 두자리수, 세자리수 숫자가 있는 부분에 대한 처리이다.
자바에서 compare 하는 로직을 앞/뒤 값 비교가 아닌 두 숫자를 앞 뒤로 붙인 값들을 (ex : 5, 40 -> 5 40, 40 5)
기준으로 비교하며 더 큰 숫자 순서로 정렬해주는 것이다.
그리고 큰 값이므로 숫자가 아닌 문자열로 처리하는데, 0에 대한 예외처리 로직을 넣어주고 끗
public String largestNumber(int[] nums) {
int[] sorted = Arrays.stream(nums)
.boxed()
.sorted(this::compare)
.mapToInt(i -> i).toArray();
StringBuilder sb = new StringBuilder();
for(int num : sorted) {
sb.append(num);
}
String res = sb.toString();
return res.charAt(0) == '0' ? "0" : res;
}
private int compare(Integer a, Integer b) {
String str1 = String.format("%d%d", a, b);
String str2 = String.format("%d%d", b, a);
return str2.compareTo(str1);
}
'Computer Science > 알고리즘' 카테고리의 다른 글
[Leetcode] Teemo Attacking (0) | 2020.09.28 |
---|---|
[Leetcode] Find the Difference (0) | 2020.09.25 |
[Leetcode] Car Pooling (1) | 2020.09.22 |
[Leetcode] Multiply Strings (0) | 2020.09.15 |
[정올] 순서찾기 (문제번호 : 2437) (0) | 2020.02.17 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- CARDANO
- 암호화폐
- DP
- 스프링
- 스프링 시큐리티
- vuejs
- Redis
- Spring
- 블록체인
- 알고리즘
- gRPC
- white paper
- k8s
- 백준
- excel parsing
- Bruteforce
- Blockchain
- SpringBoot
- 비트코인
- 사토시 나가모토
- architecture
- Nealford
- leetcode
- 동적계획법
- Java
- 카르다노
- kubernetes
- Vue.js
- Bitcoin
- 아키텍처
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 27 | 28 |
글 보관함