剑指 offer java day16 排序

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值