My simple Java code beats 96.5%


  • 0
    E
    public class Solution {
        public void nextPermutation(int[] nums) {
            //find the longest ascending sequence
            int i = nums.length - 1;
            while(i>=1&&nums[i]<=nums[i - 1]) i--;
            if(i>0){
                int target = nums[i - 1];
                int dif = Integer.MAX_VALUE;
                int pos = i - 1;
                for(int j = nums.length - 1 ;j>=i;j--){
                    if(nums[j]>target&&nums[j] - target<dif){
                        dif = nums[j] - target;
                        pos = j;
                    }
                }
                int temp = nums[i - 1];
                nums[i - 1] = nums[pos];
                nums[pos] = temp;
            }
            //reverse
            for(int left = i, right = nums.length - 1 ;left<right;left++,right--){
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
            }
        }
    }
    

Log in to reply
 

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