算法准备-4.20

算法准备-4.20

1. 把数组排成最小的数

  1. 描述:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

  2. 思路:这题实际上是对字符串进行排序,排序的规则是任两个数字对应的字符连接的顺序不同的结果较小的那个排在前面,按照快排的思想进行修改

  3. 题解:

    class Solution {
        public String minNumber(int[] nums) {
            String[] res=new String[nums.length];
            for(int i=0;i<nums.length;i++)
            {
                res[i]=String.valueOf(nums[i]);
            }
            fastsort(res,0,nums.length-1);
            StringBuilder ress=new StringBuilder();
            for(String s:res)
            {
                ress.append(s);
            }
            return ress.toString();
        }
        public void fastsort(String[] strs,int low,int high){
            if(low>=high) return;
            int i,j;
            i=low;
            j=high;
            while(i<j)
            {
                while((strs[j]+strs[low]).compareTo(strs[low]+strs[j])>=0&&i<j) j--;
                while((strs[i]+strs[low]).compareTo(strs[low]+strs[i])<=0&&i<j) i++;
                if(i<j)
                {
                    String temp=strs[i];
                    strs[i]=strs[j];
                    strs[j]=temp;
                }
            }
            String temp2=strs[low];
            strs[low]=strs[i];
            strs[i]=temp2;
            fastsort(strs,low,i-1);
            fastsort(strs,i+1,high);
        }
    }
    

2. 丑数

  1. 描述:我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。

  2. 思路:动态规划,已知一个长度为n的丑数序列,那么第n+1个丑数必定是由序列中的某个数乘2或3或5得到的,且是最接近第n个丑数的。

  3. 题解:

    class Solution {
        public int nthUglyNumber(int n) {
            int[] res=new int[n];
            res[0]=1;
            int a,b,c;
            a=0;
            b=0;
            c=0;
            for(int i=1;i<n;i++)
            {
                int next1=res[a]*2;
                int next2=res[b]*3;
                int next3=res[c]*5;
                res[i]=Math.min(Math.min(next1,next2),next3);
                if(res[i]==next1) a++;
                if(res[i]==next2) b++;
                if(res[i]==next3) c++;
            }
            return res[n-1];
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值