Java Interesting Solution


  • 0
    S
    public class Solution {
        public void nextPermutation(int[] nums) {
            int len = nums.length, temp;
            
            if (len < 2)
                return;
            int i,j;
            
            int incIndex = -1;
            
            for (i = len -2;i>= 0;i--) {
                if(nums[i] < nums[i+1]) {
                    incIndex = i;
                    break;
                }
            }
            
            if(incIndex < 0) {
                Arrays.sort(nums);
                return;
            }
            
            int nextIndex = incIndex + 1;
            
            for (i = nextIndex + 1;i<len;i++) {
                if(nums[i] > nums[incIndex] && nums[i] < nums[nextIndex])
                    nextIndex = i;
            }
            
            temp = nums[incIndex];
            nums[incIndex] = nums[nextIndex];
            nums[nextIndex] = temp;
            
            int[] copy = new int[len - incIndex-1];
            
            for(i=0;i<len-incIndex-1;i++) {
                copy[i] = nums[incIndex+1+i];
            }
            
            Arrays.sort(copy);
            
            for(i=0;i<len-incIndex-1;i++) {
                nums[incIndex+1+i] = copy[i];
            }
        }
    }

Log in to reply
 

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