2 java solutions, loop & math


  • 0
    M
    public class Solution {
        
        public int arrangeCoins(int n){
            return arrangeCoins_2(n);
        }
        
        // O(1) 
        private int arrangeCoins_2(int n) {
            if(n<=0) return 0;
            return (int)(Math.sqrt(8*(long)n+1)-1)/2;
        }
        // O(n)
        private int arrangeCoins_1(int n) {
            if(n<=0) return 0;
            long sum=0;
            int i=1;
            for(; sum<=n; i++){
                sum += i;
            }
            return i-2;
        }
    }
    

Log in to reply
 

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