本题也是剑指offer系列中的试题.
本来原来的思路是之前的全排列, 将所有的可能进行排列, 然后在结果中选出最小的. 但是这样的话, 必须将所有的情况都列出来, 不能中间进行判断, 那么复杂度就很高了.
只能分享大神的思路了 : 将数组保存在一个 list 中, 然后用 Collections.sort 对其进行排序, 使用自己定义的排序器即可. 对于排序方法的重写也十分巧妙.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Solution {
public String PrintMinNumber(int [] numbers) {
ArrayList<Integer> list = new ArrayList<>();
int n = numbers.length;
for(int i = 0; i < n; i++)
list.add(numbers[i]);
Collections.sort(list, new Comparator<Integer>(){
public int compare(Integer str1, Integer str2) {
String s1 = str1 +"" + str2;
String s2 = str2 +"" + str1;
return s1.compareTo(s2);
}
});
StringBuffer s= new StringBuffer();
for(int j:list)
s.append(j);
return s.toString();
}
}
这段代码的核心部分在于排序器重写的部分 :
Collections.sort(list, new Comparator<Integer>() {
/*对 compare 方法的返回值的说明, return a negative integer, zero, or a positive integer
* as the first argument is less than, equals to, or greater than the second.
*/
@Override
public int compare(Integer o1, Integer o2) {
String s1 = o1 + "" + o2;
String s2 = o2 + "" + o1;
return s1.compareTo(s2);
}
});
从 Collections.java 的源码中可以看到 Collection.sort 的排序有两种方式 :
public static <T extends Comparable<? super T>> void sort( List<T> list) {
list.sort(null);
}
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
使用第一种排序的默认结果是升序排列的, 如果自定义排序方式, 那么就得使用第二种排序, 通过 Comparator 的 compare() 方法来实现, 如同本题的方式. 在对 compare() 方法的重写中, 返回值的说明 :
这里还想说明一下 compareTo 方法, 源码如下 :
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while(k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if(c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
从源码中可以看到, String 的 compareTo() 方法, 该方法是比较两个字符串对应位置的字符, 比较其 ASCII 值, 如果字符不一样, 就返回字符之差, 否则返回长度之差.
从牛客网上的评论可以看到, 这里的返回结果的升序或者降序排列让很多人困惑, 我们来看源码中对于 compare 方法的描述
Compares its two arguments for order. Returns a negative integer, zero , or a positive integer as the first argument is less than, equal to, or greater than the second.
这里并没有说明是升序还是降序排列, 只是说明了如何从返回值的大小中得到待比较的两个数的相对大小关系.
查阅官方文档看到下面的说明 :
For the mathematically inclined, the relation that defines the imposed ordering that a given comparator c imposes on a given set of objects S is : {(x, y) such that c.compare(x, y) <= 0 }
这句话应该就解释了排序的规则了, 从后往前看, 按照 compare 返回值大于等于 0 的顺序升序排列.