Sharing my java code


  • 0
    M
    public class Solution {
        public void nextPermutation(int[] num) {
            int i=num.length - 1;
            while (i>0 && num[i-1] >= num[i]){
                i--;
            }
            if (i==0)
                mirror(num);
            else{
                int minOfGreater = Integer.MAX_VALUE;
                int minOfGreaterInd = -1;
                for (int j=i; j<num.length; j++){
                    if (num[j] > num[i-1] && num[j] < minOfGreater){
                        minOfGreater = num[j];
                        minOfGreaterInd = j;
                    }
                }
                swap(num, minOfGreaterInd, i-1);
                Arrays.sort(num, i, num.length);
            }
        }
        
        private void mirror(int[] num){
            for (int i=0; i<num.length/2; i++){
                swap(num, i, num.length - 1 - i);
            }
        }
        
        private void swap(int[] num, int i, int j){
            int temp = num[i];
            num[i] = num[j];
            num[j] = temp;
        } 
    }

Log in to reply
 

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