My 515 ms O(n) solution in C#


  • 0
    C
    public void NextPermutation(int[] nums)
            {
                int i; bool possible = false;
                for (i = nums.Length - 1; i > 0; i--)
                {
                    if (nums[i - 1] < nums[i]) { possible = true; break; }
                }
                if (!possible) i = 0;
                Reverse(nums, i);
    
                if (possible)
                {
                    for (int j = i; j < nums.Length; j++)
                    {
                        if (nums[i - 1] < nums[j])
                        {
                            int temp = nums[i - 1];
                            nums[i - 1] = nums[j];
                            nums[j] = temp;
                            return;
                        }
                    }
                }
                
            }
    
            private void Reverse(int[] nums, int i)
            {
                int j = nums.Length - 1;
                int temp;
                while (i < j)
                {
                    temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
    
                    i++; j--;
                }
            }
    

Log in to reply
 

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