2022/08/02------丑数

题目描述

剑指 Offer 49. 丑数

解题思路

解题思路一:边增数边做判断,充分利用前面保存的丑数。缺点:超出时间限制。

优化思路:不应该一个一个数值地来判断,要充分利用大丑数是由小丑数来组成的,从而得到前n个数的具体值。避免无用的判断,优化时间效率。

代码实现

思路一代码实现:

package cz;

import java.util.ArrayList;
import java.util.List;

public class NthUglyNumber_0802 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int n=11;
		System.out.print(nthUglyNumber(n));

	}	
	public static int nthUglyNumber(int n) {
		
		List<Integer> mlist=new ArrayList<>();
		int count=1;
		int res=1;
		mlist.add(res);
		while(true) {
			
			if(count==n)break;
			else {
				res+=1;
				if(res%2==0&&mlist.contains(res/2)||res%3==0&&mlist.contains(res/3)||res%5==0&&mlist.contains(res/5)) {
					count++;
					mlist.add(res);
				}
			}
		}		
		return res;
    }

}

优化思路代码实现如下:

package cz;

import java.util.ArrayList;
import java.util.List;

public class NthUglyNumber_0802 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int n=11;
		System.out.print(nthUglyNumber(n));

	}
	
	
	
	public static int nthUglyNumber(int n) {
		
		int[] ugly=new int [n];
		ugly[0]=1;
		int i=0,j=0,k=0;
		
		for(int index=1;index<n;index++)
		{
			int temp=Math.min(ugly[i]*2, Math.min(ugly[j]*3, ugly[k]*5));
			//避免重复
			if(temp==ugly[i]*2)i++;
			if(temp==ugly[j]*3)j++;
			if(temp==ugly[k]*5)k++;
			ugly[index]=temp;
		}
		
		
		return ugly[n-1];

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值