leetcode 179 最大數
https://leetcode.cn/problems/largest-number/description/
給定一組非負整數 nums,重新排列每個數的順序(每個數不可拆分)使之組成一個最大的整數。
注意:輸出結果可能非常大,所以你需要返回一個字符串而不是整數。
示例 1:
輸入:nums = [10,2]
輸出:"210"
示例 2:
輸入:nums = [3,30,34,5,9]
輸出:"9534330"
我這是通過愚蠢的觀察得出的規律, 答案的題解里有另外一種方法和證明。
我的主題思路是排序,不過怎么排是關鍵, 設兩個排序string分別是A, B
名詞說明:
- 可比較范圍內: 兩個值都沒有越界
首先, 對于在彼此可比較范圍內,如果出現不一樣的字符,則他們的順序就是這兩個不同字符的順序: order(A,B) = order(char_A,char_B)
當超出某個的可比較范圍, 則來到了某個長數組的地方, 設長的為lon, 短的為shor, 并且當來到此種情況是, shor一定是lon的前綴,且lon = y * shor + x * CHAR
其中 y >= 1, 0 <= x <= len(shor)
則對于shor 與 lon的比較其實是 : shor + lon 與 lon + shor 的比較, 粗略上來講,可以直接比較:shor + lon 與 lon + shor
也可以比較 shor 與 x*CHAR
shor + long = shor shor shor x*Char
long + shor = shor shor x*Char shor
所以: 如果shor == xCHAR 則相等, 如果 shor > xCHAR 則 shor + long 更大, 則shor 更大, 如果 shor < x*CHAR , 則lon + shor 更大,則 lon 更大。
(所以,這里的代碼其實寫復雜了)
class Solution {
public String largestNumber(int[] nums) {
String[] ss = new String[nums.length];
for(int i =0;i < nums.length; ++ i) {
ss[i] = String.valueOf(nums[i]);
}
Arrays.sort(ss, new Comparator<String>() {
public int compare(String a, String b) {
int i = 0;
for( ; i < a.length() && i < b.length(); ++ i) {
if(a.charAt(i) != b.charAt(i)) {
return ( a.charAt(i) - b.charAt(i));
}
}
if(i == a.length() && i == b.length()) {
return 0;
}
String lon = i != a.length() ? a:b;
String shor = i == a.length() ? a:b;
int j = i;
while( j < lon.length() && lon.charAt(j % i) == lon.charAt(j)) {
j ++;
}
if(j < lon.length()) { // lon.charAt(j % i) != lon.charAt(j)
int v = lon.charAt(j) - lon.charAt(j % i);
// v > 0 lon is bigger, v < 0 shor is bigger
return v > 0 ? (a == lon ? 1 : -1) : (a == shor ? 1 : -1);
}
// j == lon.length()
int t = j % i;
char shorLeadingCharToCompare = '\0';
char lonLeadingCharToCompare = '\0';
while( t < i) {
shorLeadingCharToCompare = lon.charAt(t % i);
lonLeadingCharToCompare = lon.charAt(t - j%i);
if(shorLeadingCharToCompare - lonLeadingCharToCompare != 0) {
break;
}
++ t;
}
if(t == i) {
return 0;
}
//char shorLeadingCharToCompare = lon.charAt(j % i);
//char lonLeadingCharToCompare = lon.charAt(0);
int v = shorLeadingCharToCompare - lonLeadingCharToCompare;
// v > 0 shor is bigger v < 0 lon is bigger
return v > 0 ? (a == shor ? 1 : -1) : (a == lon ? 1 : -1);
}
});
System.out.println(Arrays.deepToString(ss));
StringBuilder sb = new StringBuilder();
for(int i = ss.length-1; i >= 0; -- i) {
sb.append(ss[i]);
}
String tmpAns= sb.toString();
int i = 0;
boolean startingWith0 = true;
for(; i < tmpAns.length() - 1; ++i) {
if(startingWith0 && tmpAns.charAt(i) == '0'){
}else {
break;
}
}
return tmpAns.substring(i);
}
}