zoukankan      html  css  js  c++  java
  • LeetCode.970-强大的整数(Powerful Integers)

    这是悦乐书的第367次更新,第395篇原创

    01 看题和准备

    今天介绍的是LeetCode算法题中Easy级别的第229题(顺位题号是970)。给定两个正整数xy,如果对于某些整数i >= 0j >= 0等于x^i + y^j,则整数是强大的。

    返回值小于或等于bound的所有强大整数的列表。

    你可以按任何顺序返回答案。在你的答案中,每个值最多应出现一次。例如:

    输入: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

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

    注意

    • 1 <= x <= 100

    • 1 <= y <= 100

    • 0 <= bound <= 10^6

    02 第一种解法

    直接翻译题目即可,没有什么特殊的技巧,但是需要注意一点,因为判断条件时x或者y的几次方小于bound,如果x或者y为1的时候,1的任何次方都会是1,会一直小于bound,会造成死循环。

    public List<Integer> powerfulIntegers(int x, int y, int bound) {
        Set<Integer> set = new HashSet<Integer>();
        for (int i=0; Math.pow(x, i) < bound; i++) {
            for (int j=0; Math.pow(y, j) < bound; j++) {
                int sum = (int)Math.pow(x, i)+(int)Math.pow(y, j);
                if (sum <= bound) {
                    set.add((int)sum);
                }
                // y等于1时,容易造成死循环,要结束掉
                if (y == 1) {
                    break;
                }
            }
            // x等于1时,容易造成死循环,要结束掉
            if (x == 1) {
                break;
            }
        }
        return new ArrayList<>(set);
    }
    

    03 第二种解法

    针对上面第一种解法,我们也可以不借助Math类的pow方法,用累计相乘替代,思路都是一样的。

    public List<Integer> powerfulIntegers2(int x, int y, int bound) {
        Set<Integer> set = new HashSet<Integer>();
        for (int i=1; i<bound; i *= x) {
            for (int j=1; j<bound; j *= y) {
                if (i+j <= bound) {
                    set.add(i+j);    
                }
                if (y == 1) {
                    break;
                }
            }
            if (x == 1) {
                break;
            }
        }
        return new ArrayList<>(set);
    }
    

    04 小结

    算法专题目前已连续日更超过七个月,算法题文章235+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

    以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

  • 相关阅读:
    Java程序的设计环境配置
    Java总结之Java简介
    Python Panda
    Python with MYSQL
    python string与list互转
    Filter/replace
    django-pagination分页
    python 链接MS SQL
    Django 文件下载功能
    Sharepoint list webpart
  • 原文地址:https://www.cnblogs.com/xiaochuan94/p/11105760.html
Copyright © 2011-2022 走看看