C# 3 steps


  • 0
    Y
    public class Solution {
        public void NextPermutation(int[] nums) {
            int n = nums.Length;
            int runner=n-1;
            while(runner>0 && nums[runner-1] >= nums[runner])
            {runner--;}
            if(runner == 0)
            {
                Array.Sort(nums);
                return;
            }
            //find first num > runner
            int s = 0;
            for(int i=n-1;i>=runner;i--)
            {
                if(nums[i]>nums[runner-1])
                {
                    s = i;
                    break;
                }
            }
            //swap with first big number
            swap(nums, runner - 1, s);
            //partal sort 
            if(runner<n-1)
                Array.Sort(nums,runner,n-1-runner+1);
        }
        private void swap(int[] nums, int i, int j)
        {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }

Log in to reply
 

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