4kyu Twice linear

4kyu Twice linear

题目背景:

Task
Consider a sequence u where u is defined as follows:

1. The number u(0) = 1 is the first one in u.
2. For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too.
3. There are no other numbers in u.

Given parameter n the function dbl_linear (or dblLinear…) returns the element u(n) of the ordered (with <) sequence u (so, there are no duplicates).

Example

u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]
dbl_linear(10) should return 22

题目分析:
本道题目的思路很清晰,就是不断迭代数组中的元素,以及该元素 u 的 2 * u + 1 和 3 * u + 1,我们需要做的是如何把这些元素按照从小到大的顺序排序。简单的思路就是借用队列去维护 2 * u + 1,及 3 * u + 1 的非记录元素,每个队列里面的数据是从小到大的排序,每一次都是比对两个队列的队首元素,然后次数 +1。

AC代码:

#include <queue>

class DoubleLinear
{
public:
    static int dblLinear(int n);
};

int DoubleLinear::dblLinear(int n) {
    std::queue<int> q2;
    std::queue<int> q3;
    int tmp = 1, cnt = 0;
    while( cnt != n ) {
        q2.push(tmp * 2 + 1);
        q3.push(tmp * 3 + 1);
        if ( q2.front() < q3.front() ) {
            tmp = q2.front();
            q2.pop();
        }
        else if ( q2.front() > q3.front() ) {
            tmp = q3.front();
            q3.pop();
        }
        else {
            tmp = q2.front();
            q2.pop();
            q3.pop();
        }
        cnt++;   
    }
    return tmp;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值