剑指offer[45、46]

剑指 Offer 45. 把数组排成最小的数

题目

在这里插入图片描述

思路

快排+特殊规则;
在这里插入图片描述

代码

class Solution {
    public String minNumber(int[] nums) {
        String[] strs = new String[nums.length];
        for(int i = 0; i < nums.length; i++)
            strs[i] = String.valueOf(nums[i]);
        fastSort(strs, 0, strs.length - 1);
        StringBuilder res = new StringBuilder();
        for(String s : strs)
            res.append(s);
        return res.toString();
    }
    void fastSort(String[] strs, int l, int r) {
        if(l >= r) return;
        int i = l, j = r;
        String tmp = strs[i];
        while(i < j) {
            while((strs[j] + strs[l]).compareTo(strs[l] + strs[j]) >= 0 && i < j) j--;
            while((strs[i] + strs[l]).compareTo(strs[l] + strs[i]) <= 0 && i < j) i++;
            tmp = strs[i];
            strs[i] = strs[j];
            strs[j] = tmp;
        }
        strs[i] = strs[l];
        strs[l] = tmp;
        fastSort(strs, l, i - 1);
        fastSort(strs, i + 1, r);
    }
}
class Solution:
    def minNumber(self, nums: List[int]) -> str:
        def fast_sort(l , r):
            if l >= r: return
            i, j = l, r
            while i < j:
                while strs[j] + strs[l] >= strs[l] + strs[j] and i < j: j -= 1
                while strs[i] + strs[l] <= strs[l] + strs[i] and i < j: i += 1
                strs[i], strs[j] = strs[j], strs[i]
            strs[i], strs[l] = strs[l], strs[i]
            fast_sort(l, i - 1)
            fast_sort(i + 1, r)
        
        strs = [str(num) for num in nums]
        fast_sort(0, len(strs) - 1)
        return ''.join(strs)

剑指 Offer 46. 把数字翻译成字符串

题目

在这里插入图片描述

思路

在这里插入图片描述

代码

class Solution {
    public int translateNum(int num) {
        String str=String.valueOf(num);
        int a=1,b=1;
        for(int i=2;i<=str.length();i++){
            String tmp=str.substring(i-2,i);
            int c=tmp.compareTo("10")>=0&&tmp.compareTo("25")<=0?a+b:b;
            a=b;
            b=c;
        }
        return b;

    }
}
class Solution:
    def translateNum(self, num: int) -> int:
        st=str(num)
        a,b=1,1
        for i in range(2,len(st)+1):
            tmp=st[i-2:i]
            if tmp>='10' and tmp<='25':
                c=a+b
            else:
                c=b
            a=b
            b=c
        return b
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值