zoukankan      html  css  js  c++  java
  • 丑数

    题目:把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

    思路:暴力会超时,需要在计算的时候最好是能够利用上一次的计算结果。在算ugly number的时候可以跳过所有非ugly number的数字。因为一个ugly number后面的ugly number一定是上一个ugly number的2,3,5的倍。。。

    实现代码:

    public class Solution {
        public int GetUglyNumber_Solution(int index) {
            if(index <= 0)
                return 0;
            
            int[] arr = new int[index];
            arr[0] = 1;
    
            int[] arr2 = arr, arr3 = arr, arr5 = arr;
            int next = 1, i = 0, j = 0, k = 0;
            while(next < index) {
                int min = minOf3(arr2[i]*2, arr3[j]*3, arr5[k]*5);
                arr[next] = min;
                while(arr2[i] * 2 <= arr[next]) {
                    i ++;
                }
                while(arr3[j] * 3 <= arr[next]) {
                    j ++;
                }
                while(arr5[k] * 5 <= arr[next]) {
                    k ++;
                }
                next ++;
            }
            int ugly = arr[next - 1];
            return ugly;
        }
        
        public int minOf3(int a, int b, int c) {
            int t = a > b ? b : a;
            return t > c ? c : t;
        }
    }
  • 相关阅读:
    正则表达式
    request库解析
    urllib库解析
    爬虫入门基本原理
    图的遍历dfs和bfs
    KMP算法
    Linux操作系统实验-线程同步
    Leetcode 183场周赛
    并查集--Disjoint Set
    C#杂乱知识汇总
  • 原文地址:https://www.cnblogs.com/wxisme/p/5469930.html
Copyright © 2011-2022 走看看