Java solution


  • 0
    R
    public class Solution {
        public void nextPermutation(int[] num) {
                   int i = num.length-1;
    
            while (i > 0){
                if (num[i-1] < num[i]){
                    break;
                }
                i--;
            }
    
            if (i == 0){
                int k= num.length-1;
                while (i<k){
                    swap(num , i , k);
                    i++;
                    k--;
                }
                return;
            }
    
            int j= num.length-1;
            while (num[j] <= num[i-1]){
                j--;
            }
            swap(num , i-1 , j);
    
            while (j+1 < num.length && num[j] <= num[j+1]){
                swap(num , j , j+1);
                j++;
            }
    
            int k = num.length-1;
            while (i<k){
                swap(num , i , k);
                i++;
                k--;
            }
            
        }
           private static void swap (int [] array , int i , int j){
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
    

Log in to reply
 

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