LeetCode 970. Powerful Integers (强整数)

题目标签:HashMap

  题目让我们找出所有独一的powerful integers 小于bound的情况下。

  把 x^i 看作 a;把 y^j 看作b, 代入for loop,把所有的情况都遍历一遍。

  参考的这种方法,用for loop 写的比较简洁易懂。

  具体看code。

 

Java Solution:

Runtime: 4 ms, faster than 99.85% 

Memory Usage: 37.5 MB, less than 7.69%

完成日期:03/13/2019

关键点:把 x^i 看作 a;把 y^j 看作b, 代入for loop

class Solution 
{
    public List<Integer> powerfulIntegers(int x, int y, int bound) 
    {
        Set<Integer> result = new HashSet<>();

        for(int a = 1; a < bound; a *= x) 
        {
            for(int b = 1; a + b <= bound; b *= y) 
            {
                result.add(a + b);
                
                if(y == 1) 
                    break;
            }
            
            if(x == 1) 
                break;
        }
        
        return new ArrayList<>(result);
    }
}

参考资料:https://leetcode.com/problems/powerful-integers/discuss/214197/Java-straightforward-try-all-combinations

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2019-03-18 03:20  Jimmy_Cheng  阅读(432)  评论(0编辑  收藏  举报