:( Why my solution is slow? java 70ms


  • 0
    D

    Could some one point out why my solution is this slow? I saw similar solutions out there that run < 10ms
    Thanks in advance.

    public class Solution {
        public boolean isHappy(int n) {
           List<Integer> set=new ArrayList<Integer>();
           while(!set.contains(n)){
             set.add(n);
             System.out.println(n);
             n=squaresum(n);
             if(n==1) return true;
        }
        return false;
    }
    
    public int squaresum(int n){
        int sum=0;
        while(n!=0){
            sum=sum+(n%10)*(n%10);
            n=n/10;
        }
        return sum;
    }
    

    }


  • 0

    Because printing is slow. Just remove that.


  • 0
    D

    Oh haha yeah, I forgot about it. Thanks!


  • 0
    C

    Use hashSet is better. Every loop you would query the List.


  • 0

    That actually makes it slower, not faster. It's really just the printing. Removing the printing brings it from 70ms down to 5ms, and then using HashSet brings it up to 6ms.


Log in to reply
 

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