Sunday, August 4, 2019

Leetcode 970: Powerful Integers

https://leetcode.com/problems/powerful-integers/description/



Notes:

The example given above is somehow misleading. One way to solve this problem is scan from 0 to bound, and check each word can be write as required. Obviously this way is too slow, since its time complexity is O(N^2).

A different way to think about it is that there are not many values of x^i in the bound range; the same is to y^j. Thus, we can check all the possible sums from them, and save the ones that fit the requirement.

Some details:
a): when x = 1 or y = 1;
b): there should be no redundant in the result.

See the code below,

  1. class Solution {
  2. public:
  3.     vector<int> powerfulIntegers(int x, int y, int bound) {
  4.         vector<int> res;
  5.         set<int> st;
  6.         for(int i=1; i<bound; i *= x) {
  7.             for(int j=1; i+j<=bound; j *= y) {
  8.                 if(st.count(i+j)) continue;
  9.                 st.insert(i+j);
  10.                 res.push_back(i+j);
  11.                 if(y==1) break;
  12.             }
  13.             if(x==1) break;
  14.         }
  15.         return res;
  16.     }
  17. };

No comments:

Post a Comment