Sort
Task
1. κ°μ₯ ν° μ in Programmers (Level 2)
π Problem
https://programmers.co.kr/learn/courses/30/lessons/42746
π The point
- Used **Arrays.sort(array, Comparator
)** Itβs one of the fast way to sort array
[Different type 1]
1
Arrays.sort(array)
- If array is primitive type such as int[] and char[], it use Dual-Pivot QuickSort (InsertionSort + QuickSort).
- If array is Object type such as String[] and Integer[], it use TimSort (InsertionSort + MergeSort).
β
- [Different type 2]
1 2 3 4 5
Arrays.sort(array, new Comparator<String>() { @Override public int compare(String o1, String o2) { return ((o2 + o1).compareTo(o1 + o2)); });
π Answer
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
29
30
31
32
33
34
import java.util.Arrays;
class Solution {
public String solution(int[] numbers) {
// Convert int array to String array
String[] result = new String[numbers.length];
for (int i = 0; i < numbers.length; i++)
result[i] = String.valueOf(numbers[i]);
// Sort (lambda expression)
// specific meaning : String.compareTo(String)
// why (o2 + o1)? because it sort datas by dscending order
// then, (o1 + o2) -> become ascending order
Arrays.sort(result, (o1, o2) -> (o2 + o1).compareTo(o1 + o2));
// [Same expression]
// Comparator<String> comp = (o1, o2) -> (o2 + o1).compareTo(o1 + o2);
// Arrays.sort(result, comp);
// If there are multiple zero, return only 0
if (result[0].equals("0")) {
return "0";
}
// Convert String array to String
String answer = "";
for (String a : result) answer += a;
return answer;
}
}
The source : https://haeng-on.tistory.com/7
Donβt forget the contents of OCPJP! Itβs quite useful on coding test.
Comments powered by Disqus.