Java Solution, Similar to others by finding 1st decreasing, swapping and then reversing


  • 0
    E
    public class Solution {
        public void nextPermutation(int[] nums) {
            int index=-1;
            //find the first decreasing element
            for(int i=nums.length-1;i>0;i--){
                if(nums[i]>nums[i-1]){
                    index=i-1;
                    break;
                }
            }
            if(index==-1){
                Arrays.sort(nums);
                return;
            }
            //swap it with the element which is just larger than the decreasing element as above
            int diff=Integer.MIN_VALUE,index2=-1;
            for(int i=index+1;i<nums.length;i++){
                if(diff<=nums[index]-nums[i] && nums[index]-nums[i]<0){
                    index2=i;
                    diff=nums[index]-nums[i];
                }
            }
            int tmp=nums[index];
            nums[index]=nums[index2];
            nums[index2]=tmp;
            //reverse the part of the array from the next index of the swapped element to the last---after the index 'index'
            ArrayList<Integer>list=new ArrayList<Integer>();
            for(int i=index+1;i<nums.length;i++){
                list.add(nums[i]);
            }
            Collections.reverse(list);
            for(int i=0;i<list.size();i++){
                nums[index+1]=list.get(i);
                index++;
            }
            return;
        }
    }
    

Log in to reply
 

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