丑数--用Java中的list实现

先对比一下不使用列表的方法:

package com.zhizhuo.linklist;

import java.util.Scanner;

public class chouShu {
	public static void main(String[] args) {
		System.out.println("求第几个丑数:");
		int n = new Scanner(System.in).nextInt();
		long r = f1(n);
		System.out.println(r);
}
	private static long f1(int n) {	
		int cnt = 0;
        //记录第几个丑数
		for (int i = 2; ; i++) {//不包括1
			int j = i;
			while(j % 2 == 0) {
				j/=2;
			}
			while(j % 3 == 0) {
				j/=3;
			}
			while(j % 5 == 0) {
				j/=5;
			}
			if(j==1) {
					cnt++;
				if(cnt==n) {
					return i;
				}
			}
		}
	}
}

 下面是使用list的方法:

package com.zhizhuo.linkedlist;

import java.util.LinkedList;
import java.util.Random;
import java.util.Scanner;


public class Test3 {
	public static void main(String[] args) {
		System.out.println("求第几个丑数");
		int n = new Scanner(System.in).nextInt();
		long r = f(n);
		System.out.println(r);
	}

	
	private static long f(int n) {
		// TODO Auto-generated method stub
		if(n == 1) {
			return 1;
		}
		/* 
		 * 2 4
		 * --------------------
		 * 3 6 
		 * ---------------------
		 * 5 10
		 * ---------------------
		 * 1.取头部的最小值
		 * 2.乘2,3,5,放入三个集合
		 */
		long r = 0;
		//第一步先定义出三个列表
		LinkedList<Long> list2 = new LinkedList<Long>();
		LinkedList<Long> list3 = new LinkedList<Long>();
		LinkedList<Long> list5 = new LinkedList<Long>();
		//将2,3,5分别添加到三个列表中
		list2.add(2L);
		list3.add(3L);
		list5.add(5L);
		//
		for (int i = 0; i < n; i++) {
			long a = list2.getFirst();
			long b = list3.getFirst();
			long c = list5.getFirst();
            //将三个列表中最小的一个提取出来
			r = Math.min(a, Math.min(c, b));
			if(a == r)	list2.remove();
			if(b == r)	list3.remove();
			if(c == r)	list5.remove();
            //乘2,3,5,放入三个集合
			list2.add(r*2);
			list3.add(r*3);
			list5.add(r*5);
		}
		return r;
	}
}

 

当输入较大的数值时,不用list的方法明显需要较长时间。 因为前者需要两层循环,而后者,只需一层,相对时间复杂度较小。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值