Cracking the Coding Interview 10.7

Design an algorithm to find the kth number such that the only prime factors are 3,5 and 7

 

方法一:

a[i]=min{a[s1]*3,a[s2]*5,a[s3]*7};

s1<i,s2<i,s3<i   &&    a[s1]*3>a[i-1],a[s2]*3>a[i-1],a[s3]*7>a[i-1]

时间复杂度O(n^2)

#include<stdio.h>

int min(int a,int b,int c)
{
    int smallest = a<b?a:b;
    smallest = smallest<c?smallest:c;
    return smallest;
}

int func(int k)
{
    int m3=0;
    int m5=0;
    int m7=0;
    int *p = new int[k+1];
    p[0]=1;
    for(int i=1;i<=k;i++)
    {
        for(int j=0;j<i;j++)
        {
            if(p[j]*7>p[i-1])
            {
                m7=p[j]*7;
                break;
            }
        }
        for(int j=0;j<i;j++)
        {
            if(p[j]*5>p[i-1])
            {
                m5=p[j]*5;
                break;
            }
        }
        for(int j=0;j<i;j++)
        {
            if(p[j]*3>p[i-1])
            {
                m3=p[j]*3;
                break;
            }
        }
        p[i]=min(m3,m5,m7);
    }
    int r = p[k];
    delete[] p;
    p = NULL;
    return r;
}

int main()
{
    int k=1024;
    printf("%dth:%d\n",k,func(k));
    return 0;
}

方法二:

将1填入输出数组的第一位,然后准备三个队列Q3,Q5,Q7,分别压入1*3,1*5,1*7

第i位就是三个队列的队首元素中最小的,然后将该元素从队列取出:

    如果是从Q3取出,则将该数分别乘以3,5,7,再将三个数分别插入到Q3,Q5,Q7队尾

    如果是从Q5取出,则将该数分别乘以5,7,再将两个数分别插入到Q5,Q7队尾

    如果是从Q7取出,则将该数乘以7,再将结果插入到Q7队尾

    直到取出第K+1位(1不算)

    时间复杂度O(n)

#include<iostream>
#include<deque>

using namespace std;

int func(int k)
{
    deque<int>Q3;
    deque<int>Q5;
    deque<int>Q7;
    int pi=1;
    Q3.push_back(3);
    Q5.push_back(5);
    Q7.push_back(7);
    for(int i=1;i<k+1;i++)
    {
        if(Q3.front()<Q5.front() && Q3.front()<Q7.front())
        {
            pi=Q3.front();
            Q3.pop_front();
            Q3.push_back(3*pi);
            Q5.push_back(5*pi);
            Q7.push_back(7*pi);
        }
        else if(Q5.front()<Q3.front() && Q5.front()<Q7.front())
        {
            pi=Q5.front();
            Q5.pop_front();
            Q5.push_back(5*pi);
            Q7.push_back(7*pi);
        }
        else if(Q7.front()<Q3.front() && Q7.front()<Q5.front())
        {
            pi=Q7.front();
            Q7.pop_front();
            Q7.push_back(7*pi);
        }
        else
        {
            cout<<"error"<<endl;
        }
    }
    return pi;
}

int main()
{
    for(int k=1;k<16;k++)
    {
        cout<<k<<"th:"<<func(k)<<endl;
    }
    return 0;
}

 

posted @ 2014-09-03 16:34  米其林轮船  阅读(160)  评论(0编辑  收藏  举报