Accepted compact java solution


  • -1
    H
    public class Solution {
        public void nextPermutation(int[] num) {
            if (num == null || num.length < 2) return;
            
            int peak = num.length - 1, toSwap = peak;
            // from right find first peek, >= handle duplication numbers. 
            for (;peak > 0 && num[peak - 1] >= num[peak]; peak --); 
            // from right find first digit > num[peek - 1],
            for (;peak > 0 && toSwap > peak && num[toSwap] <= num[peak - 1]; toSwap --); 
            swap (num, peak - 1, toSwap);
            Arrays.sort(num, peak, num.length);// third parameter is length, not length - 1
        }
        
        private void swap(int[] num, int i, int j) {
            if (i >= 0)
                int t = num[i]; num[i] = num[j]; num[j] = t;
        }
     }

Log in to reply
 

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