class Solution {
public String crackPassword(int[] password) {
String result = "";
String[] passwords = new String[password.length];
for (int i = 0; i < password.length; i++) {
passwords[i] = Integer.toString(password[i]);
}
Arrays.sort(passwords, (a, b) -> (a + b).compareTo(b + a));
for (String psw : passwords) {
result += psw;
}
return result;
}
}
class Solution {
public String crackPassword(int[] password) {
int n = password.length;
String[] strs = new String[n];
for(int i = 0; i < n; i++){
strs[i] = String.valueOf(password[i]);
}
quickSort(strs, 0, n-1);
StringBuilder sb = new StringBuilder();
for(String s : strs){
sb.append(s);
}
return sb.toString();
共以下 11 个回答
快排
时间复杂度O(nlogn)
空间复杂度O(n)
解题思路
– 1、把int数组转换成string数组
– 2、两个字符组合,比如34和5 ,组成345 或者 534,一定是“小”的34在前面。以此类推到数组里面的所有元素,把“最大值”(此处的最大的判断标准不是用int去判断,而是通过组合数去判断的)放在最右边,把最小值放在最左边,转换成了一个排序问题
– 3、采用快排进行排序string数组
– 4、组合string数组成一个字符串
【题解1】
思路: 使用冒泡排序的方式 对数组进行处理,
class Solution {
public String crackPassword(int[] password) {
int n = password.length;
String[] strs = new String[n];
for(int i = 0; i < n; i++){
strs[i] = String.valueOf(password[i]);
}
quickSort(strs, 0, n-1);
StringBuilder sb = new StringBuilder();
for(String s : strs){
sb.append(s);
}
return sb.toString();
}
时间:O(lgn)
空间:O(n)
思路:转换为字符串进行拼接,比较大小
时间复杂度:O(n)
空间复杂度:O(n)
自定义排序规则,若x+y<y+x,则x<y。
时间复杂度O(Nlogn),空间复杂度O(N)。
//内置算法自定义排序
class Solution {
public String crackPassword(int[] password) {
int n = password.length;
String[] strs = new String[password.length];
for(int i = 0; i < password.length; i++)
strs[i] = String.valueOf(password[i]);
Arrays.sort(strs, (x, y) -> (x + y).compareTo(y + x));
StringBuilder res = new StringBuilder();
for(String s : strs)
res.append(s);
return res.toString();
}
}
用快排完成,无非就是将大小比较变成拼接后的字符串比较
On ON