LeetCode 264

思路:我们根据优先队列的性质,每次出队的元素都是依次增大的只含质因数2,3,5的正整数,我用自己写的小根堆实现的优先

   队列,生成丑数的过程请看代码

原题链接:https://leetcode-cn.com/problems/ugly-number-ii/

typedef long long lint;
#define swap(a, b) { \
    __typeof(a) __tmp = a; \
    a = b, b = __tmp; \
}

typedef struct priority_queue {
    lint *data;
    int cnt, size;
} priority_queue;

priority_queue *init(int n) {
    priority_queue *q = (priority_queue *)malloc(sizeof(priority_queue));
    q->data = (lint *)malloc(sizeof(lint) * (n + 1));
    q->cnt = 0, q->size = n;
    return q;
}

int empty(priority_queue *q) {
    return q->cnt == 0;
}

void push(priority_queue *q, lint val) {
    if (q->cnt == q->size) return ;
    q->cnt += 1;
    q->data[q->cnt] = val;
    int ind = q->cnt;
    while (ind >> 1 && q->data[ind] < q->data[ind >> 1]) {
        swap(q->data[ind], q->data[ind >> 1]);
        ind >>= 1;
    }
    return ;
}

void pop(priority_queue *q) {
    if (empty(q)) {
        return ;
    }
    q->data[1] = q->data[q->cnt--];
    int ind = 1;
    while ((ind << 1) <= q->cnt) {
        int l = ind << 1, r = ind << 1 | 1, tmp = ind;
        if (q->data[ind] > q->data[l]) {
            tmp = l;
        }
        if (r <= q->cnt && q->data[tmp] > q->data[r]) {
            tmp = r;
        }
        if (tmp == ind) break;
        swap(q->data[ind], q->data[tmp]);
        ind = tmp;
    }
    return ;
}

int top(priority_queue *q) {
    if (!empty(q)) {
        return q->data[1];
    }
    return -1;
}

int nthUglyNumber(int n) {
    priority_queue *q = init(3 * n);
    lint begin = 1, ans;
    push(q, begin);
    while (n--) {
        ans = top(q);
        pop(q);
        if (ans % 5 == 0) {
            push(q, 5 * ans);
        }
        else if (ans % 3 == 0) {
            push(q, 3 * ans);
            push(q, 5 * ans);
        }
        else {
            push(q, 2 * ans);
            push(q, 3 * ans);
            push(q, 5 * ans);
        }
    }
    return ans;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值