TLE Java using BFS

  • 1
    public class Solution {
        public boolean isUgly(int num) {
            if(num == 1) return true;
            PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
            while(!queue.isEmpty()) {
                int temp = queue.remove();
                if(temp == num) return true;
                if(temp > num) return false;
                queue.add(temp * 2);
                queue.add(temp * 3);
                queue.add(temp * 5);
            return false;

  • 0

    The concept of BFS makes Ugly Number II much easier than other methods.

  • 0

    @tony-mu101999 There are really lots of duplicates generated by your method. You have to try to remove them to improve the performance in space and time actually.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.