T1 45. 把数组排成最小的数
若拼接字符串 x + y > y+x,则 x “大于”y ; 通过传递性证明
compareTo() | 将number对象与参数比较。 如果指定的数与参数相等返回0。 如果指定的数小于参数返回 -1。 如果指定的数大于参数返回 1。 |
---|---|
valueOf(int i) | 返回 int 参数的字符串表示形式 |
public void quickSort(int[] num){
int low = 0;
int high = num.lenght - 1;
quickSort(num,low,high);
}
public void quickSort(int[] num,int low,int high){
if(low<high){
//分区 返回分区索引
int mid = getMid(num,low,high);
//左分区快速排序
quickSort(num,low,mid-1);
//右分区快速排序
quickSort(num,mid+1,high);
}
}
public int getMid(int[] num,int low,int high){
//指定基准数
int x = num[low];
while(low<high){
while(num[high]>=x && low<high) high--; //区间高端向右直到找到第一个比基准数小的j
//把比基准数小的值移到低端
num[low] = num[high];
while(num[low]<=x && low<high) low++;//区间低端向左直到找到第一个比基准数大的j
//把比基准大的值移到高端
num[high] = num[low];
}
num[i] = x;
return low;
}
题解
class Solution {
public String minNumber(int[] nums) {
StringBuilder res = new StringBuilder("");
String[] tmp = new String[nums.length];
for(int i=0;i<nums.length;i++){
tmp[i] = String.valueOf(nums[i]); //把整型数组转化为字符串数组
}
quickSort(tmp,0,tmp.length-1);
for(String s:tmp) res.append(s);
return res.toString();
}
//快速排序
public void quickSort(String[] str,int low,int high){
if(low<high){
int mid = getMid(str,low,high);
quickSort(str,low,mid-1);
quickSort(str,mid+1,high);
}
}
public int getMid(String[] str,int low,int high){
//确定基准值
String temp = str[low];
while(low<high){
// high + temp > tmp+high,则 high “大于” temp
while(low<high && (str[high]+temp).compareTo(temp + str[high])>=0) high--;
str[low] = str[high];
// low + temp < tmp+low,则 low “小于” temp
while(low<high && (str[low]+temp).compareTo(temp+str[low])<=0) low++;
str[high] = str[low];
}
str[low] = temp;
return low;
}
}
T2 61. 扑克牌中的顺子
k神的解法:条件:1.无重复(大小王除外) 2. Max - min < 5
class Solution {
public boolean isStraight(int[] nums) {
int joker = 0 ;//记录大小王的数量
Arrays.sort(nums); //数组排序 递增
for(int i=0;i<nums.length-1;i++){
if(nums[i]==0) joker++;
else if(nums[i]==nums[i+1]) return false;
}
// joker的情况 0张[0]是最小数,1张 [0]是王 [1]是最小数 2张[0],[1]是王,[2]是最小数
return nums[4] - nums[joker]<5;
}
}