求一組數字組成的最大整數三種解法
阿新 • • 發佈:2019-02-14
整理一下網上關於這道題和自己關於這道題的解法
方法一: 利用a+b和b+a進行比較選擇其中數值較大的組合方式
public class Solution {
public void maxValueNum(int[] array) {
int len = array.length;
String maxValueStr = "";
for(int i=0;i<len;i++) {
for(int j=0;j<len-1-i;j++) {
String str = "" ;
if((array[j]+str+array[j+1]).compareTo(array[j+1]+str+array[j]) > 0) {
swap(array, j, (j+1));
}
}
maxValueStr += array[len-1-i];
}
System.out.println(maxValueStr);
}
public void swap(int[] array , int a, int b) {
int tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
}
main函式:
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
int[] array = {195,23,56,235,7};
s.maxValueNum(array);
}
}
執行結果為: 75623523195
方法二: 利用compare函式特性來進行排序選擇
public class Solution1 {
public void maxValueNum(int[] array) {
int len = array.length;
String maxValueStr = "";
for(int i=0;i<len;i++) {
for(int j=0;j<len-1-i;j++) {
if(compare(array[j], array[j+1]) > 0) {
swap(array, j, (j+1));
}
}
maxValueStr += array[len-1-i];
}
System.out.println(maxValueStr);
}
public int compare(int a, int b) {
int count1 = 0;
int count2 = 0;
int middleNum1 = a;
int middleNum2 = b;
while(middleNum1 != 0) {
count1++;
middleNum1 /= 10;
}
while(middleNum2 != 0) {
count2++;
middleNum2 /= 10;
}
int num1 = (int) (a*Math.pow(10,count2)+b);
int num2 = (int) (b*Math.pow(10,count1)+a);
return num1 > num2 ? 1 : (num1 == num2 ? 0 : -1);
}
public void swap(int[] array, int a, int b) {
int tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
}
main函式:
public class Main {
public static void main(String[] args) {
Solution1 s1 = new Solution1();
int[] array = {195,23,56,235,7};
s1.maxValueNum(array);
}
}
執行結果為: 75623523195
方法三: 利用貪心演算法每次求最優值
public class Solution2 {
public void maxValueNum(int[] array) {
int len = array.length;
String maxValueStr = "";
for(int i=0;i<len;i++) {
for(int j=0;j<len-1-i;j++) {
String str = "";
if((array[j]+str).compareTo(array[j+1]+str) > 0) {
swap(array, j, (j+1));
}
}
maxValueStr += array[len-1-i];
}
System.out.println(maxValueStr);
}
public void swap(int[] array, int a, int b) {
int tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
}
main函式:
public class Main {
public static void main(String[] args) {
Solution2 s2 = new Solution2();
int[] array = {195,23,56,235,7};
s2.maxValueNum(array);
}
}
執行結果為: 75623523195