1. 程式人生 > >Leetcode970. Powerful Integers強整數

Leetcode970. Powerful Integers強整數

給定兩個非負整數 x 和 y,如果某一整數等於 x^i + y^j,其中整數 i >= 0 且 j >= 0,那麼我們認為該整數是一個強整數。

返回值小於或等於 bound 的所有強整陣列成的列表。

你可以按任何順序返回答案。在你的回答中,每個值最多出現一次。

 

示例 1:

輸入:x = 2, y = 3, bound = 10 輸出:[2,3,4,5,7,9,10] 解釋: 2 = 2^0 + 3^0 3 = 2^1 + 3^0 4 = 2^0 + 3^1 5 = 2^1 + 3^1 7 = 2^2 + 3^1 9 = 2^3 + 3^0 10 = 2^0 + 3^2

示例 2:

輸入:x = 3, y = 5, bound = 15 輸出:[2,4,6,8,10,14]

 

提示:

  • 1 <= x <= 100
  • 1 <= y <= 100
  • 0 <= bound <= 10^6

 

暴力法

如果列舉x的指數,那麼每次選擇指數後都要去得到x的冪運算結果。每次都進行冪運算,那麼就重複了很多操作。所以先把冪運算的結果儲存下來,去列舉冪運算的結果

class Solution {
public:
    vector<int> powerfulIntegers(int x, int y, int bound) 
    {
        vector<int> vx;
        vector<int> vy;
        vector<int> ans;
        map<int, bool> check;
        int tempx = 1;
        int tempy = 1;
        if(x == 1)
        {
            vx.push_back(1);
        }
        else
        {
            while(tempx <= bound)
            {
                vx.push_back(tempx);
                tempx *= x;
            }
        }
        if(y == 1)
        {
            vy.push_back(1);
        }
        else
        {
            while(tempy <= bound)
            {
                vy.push_back(tempy);
                tempy *= y;
            }
        }
        for(int i = 0; i < vx.size(); i++)
        {
            for(int j = 0; j < vy.size(); j++)
            {
                if(vx[i] + vy[j] <= bound && !check[vx[i] + vy[j]])
                {
                    check[vx[i] + vy[j]] = 1;
                    ans.push_back(vx[i] + vy[j]);
                }
            }
        }
        return ans;
    }
};

通過這道題突然想到了另外一道題,用的很簡便神奇的方法。

 

題目描述

把只包含質因子2、3和5的數稱作醜數(Ugly Number)。例如6、8都是醜數,但14不是,因為它包含質因子7。 習慣上我們把1當做是第一個醜數。求按從小到大的順序的第N個醜數。

class Solution {
public:
    int GetUglyNumber_Solution(int index) {
        if(index <= 0)
            return index;
        vector<int> res(index);
        res[0] = 1;
        int t2 = 0, t3 = 0, t5 = 0;
        for(int i = 1; i < index; i++)
        {
            res[i] = min(res[t2] * 2, min(res[t5] * 5, res[t3] * 3));
//不用else if的原因是為了去重
            if(res[i] == res[t2] * 2)
                t2++;
            if(res[i] == res[t3] * 3)
                t3++;
            if(res[i] == res[t5] * 5)
                t5++;
        }
        return res[index - 1];
    }
};