3 lines of C# codes


  • 0
    M

    We can write it in one line... Joking. Anyway, this is quite simple.

        public void NextPermutation(int[] nums)
        {
            int s = 0;
            // find the most significant num of the next permutation
            for (int i = nums.Length - 1; i > 0; i--) if (nums[i] > nums[i - 1]) { s = i-1; break; }
            // put that num in the reverse order
            for (int i = nums.Length - 1; i > s; i--) if (nums[i] > nums[s]) { Swap(ref nums[i], ref nums[s]); s++; break; }
            // reverse sort nums[s..n]
            for (int i = s; i < s + (nums.Length - s) / 2; i++) Swap(ref nums[i], ref nums[nums.Length - 1 - (i - s)]);
        }
    

    // Swap is missing. HEIHEI


  • 0
    R

    Good joke and good code.


Log in to reply
 

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