题目
思路及代码
1、字典序全排列
注意事项:
int [] 不能用String.valueOf()转成String;
Strig类型不能直接比较大小(不能用<),用s1.compareTo(s2),返回值为int类型,>0代表s1大于s2,小于0代表s1小于s2。
import java.util.ArrayList;
import java.util.*;
import java.util.Arrays;
public class Solution {
public String PrintMinNumber(int [] numbers) {
// method 1全排列解法
Arrays.sort(numbers);
//String result = String.valueOf();
String s = tos(numbers);
if (numbers.length <=1){
return s;
}
//查找
boolean flag = true;
while(flag){
for (int i = numbers.length-2;i>=0;i--){
if(numbers[i]< numbers[i+1]){
for(int j =numbers.length -1;j>i;j--){
if(numbers[j]> numbers[i]){
swaps(numbers,i,j);
reverse(numbers,i+1,numbers.length-1);
String tem = tos(numbers);
if(tem.compareTo(s) < 0){
s= tem;
}
break;
}
}
break;
}else{
if(i==0)
flag = false;
}
// break;
}
}
return s;
}
//交换
public void swaps(int [] numbers,int i,int j){
int tem =numbers[i];
numbers[i]= numbers[j];
numbers[j]= tem;
}
// 翻转
public void reverse(int [] numbers,int i,int j ){
while(i<j){
int tem = numbers[i];
numbers[i]= numbers[j];
numbers[j]= tem;
i++;
j--;
}
}
public String tos(int[] numbers){
String s= "";
for(int i =0;i<numbers.length;i++){
s = s+ numbers[i];
}
return s;
}
}
2、重定义“排序”
对于3和32,当这两个数以字符串拼接的形式拼接在一起时,即3+32=332,32+3= 323,因为332>323,因此认为3 “大于”32(当求最小排列时3应当在32前面)。
import java.util.ArrayList;
public class Solution {
public String PrintMinNumber(int [] numbers) {
if(numbers.length <=1)
return tos(numbers);
sort(numbers);
return tos(numbers);
}
//排序
public void sort(int [] numbers){
for( int i = 0; i< numbers.length;i++){
for(int j = 0; j < numbers.length-1-i;j++){
String s1 ="",s2="";
s1= s1+numbers[j]+numbers[j+1];
s2= s2+numbers[j+1]+numbers[j];
if(s1.compareTo(s2)>0){// s1> s2,也就是 numbers[j] >numbers[j+1]
//要求求最小的数,所以重新定义后的排序应为升序排列
int tem = numbers[j];
numbers [j]= numbers[j+1];
numbers[j+1]= tem;
}
}
}
}
//转换
public String tos (int [] numbers){
String s = "";
for(int i =0 ;i< numbers.length;i++)
s= s+numbers[i];
return s;
}
}