forked from Wang-Jun-Chao/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test33.java
104 lines (81 loc) · 2.87 KB
/
Test33.java
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import java.util.Comparator;
/**
* Author: 王俊超
* Date: 2015-06-11
* Time: 10:38
* Declaration: All Rights Reserved !!!
*/
public class Test33 {
/**
* 自定义的排序比较器,实现算法说明的排序原理
*/
private static class MComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
if (o1 == null || o2 == null) {
throw new IllegalArgumentException("Arg should not be null");
}
String s1 = o1 + o2;
String s2 = o2 + o1;
return s1.compareTo(s2);
}
}
/**
* 快速排序算法
*
* @param array 待排序数组
* @param start 要排序的起始位置
* @param end 要排序的结束位置
* @param comparator 自定义的比较器
*/
private static void quickSort(String[] array, int start, int end, Comparator<String> comparator) {
if (start < end) {
String pivot = array[start];
int left = start;
int right = end;
while (start < end) {
while (start < end && comparator.compare(array[end], pivot) >= 0) {
end--;
}
array[start] = array[end];
while (start < end && comparator.compare(array[start], pivot) <= 0) {
start++;
}
array[end] = array[start];
}
array[start] = pivot;
quickSort(array, left, start - 1, comparator);
quickSort(array, start + 1, end, comparator);
}
}
/**
* 题目:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,
* 打印能拼接出的所有数字中最小的一个。
* @param array 输入的数组
* @return 输出结果
*/
public static String printMinNumber(String[] array) {
if (array == null || array.length < 1) {
throw new IllegalArgumentException("Array must contain value");
}
MComparator comparator = new MComparator();
quickSort(array, 0, array.length - 1, comparator);
StringBuilder builder = new StringBuilder(256);
for (String s : array) {
builder.append(s);
}
return builder.toString();
}
public static void main(String[] args) {
String[] data = {"3", "5", "1", "4", "2"};
System.out.println(printMinNumber(data));
String[] data2 = {"3", "32", "321"};
System.out.println(printMinNumber(data2));
String[] data3 = {"3", "323", "32123"};
System.out.println(printMinNumber(data3));
String[] data4 = {"1", "11", "111"};
System.out.println(printMinNumber(data4));
String[] data5 = {"321"};
System.out.println(printMinNumber(data5));
}
}