[Java] 7 Lines O(1) space solution


  • 0
    A
    public int findDerangement(int n) {
         long a = 0, b = 1;
         long c = (n==0 || n==2) ? 1 : 0; 
         for (int i=3; i<=n; ++i){
             c = ((i-1)*(b+a))%1000000007;
             a = b;
             b = c;           
         }
         return (int) c;
    }

Log in to reply
 

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