程序员面试金典——第K个数

题目描述

有一些数的素因子只有3、5、7,请设计一个算法,找出其中的第k个数。

给定一个数int k,请返回第k个数。保证k小于等于100。

测试样例:
3
返回:7
思路:

  
  
/*
      * 时间复杂度O(N),按书中所讲,3个素数因子3、5、7分为三个队列
q3,q5,q7,其中最初存放3,5,7
      * 之后每次添加找到三个队列头中最小的数,起初为3,将3移出队列
q3后,在q3添加3*3,在q5添加3*5,q7中添加3*7
      * 此时可知q3{3*3},q5{5,3*5},q7{7,3*7}
      * 下一轮找到最小数为5,重复上述步骤,将5从q5移出,添加5*5到
q5,因为5*3已经添加过所以不需要添加到q3中
      * 将5*7添加到q7,结果q3{3*3},q5{3*5,5*5},q7{7,3*7,5*7}
      * 依次找到第k个数
      */
import java.util.*;

public class KthNumber {
    public int findKth(int k) {
        // write code here
         Queue<Integer> que3 =new LinkedList<>();
		        Queue<Integer> que5 =new LinkedList<>();
		        Queue<Integer> que7 =new LinkedList<>();
		        que3.offer(3);
		        que5.offer(5);
		        que7.offer(7);
		        int index = 1;
		        int num =3;
		        while(index<=k){
		        	//取出三个队列中最小值
		        	num = Math.min(Math.min(que3.peek(), que5.peek()), que7.peek());
		        	if(num==que3.peek()){
		        		que3.poll();
		        		que3.offer(num*3);
		        		que5.offer(num*5);
		        		que7.offer(num*7);
		        	}else if (num==que5.peek()) {
		        		que5.poll();
		        		que5.offer(num*5);
		        		que7.offer(num*7);
					}else {
						que7.poll();
						que7.offer(num*7);
					}
		        	index++;
		        }
		        return num;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值