Short C# Accepted Solution - O(n) + Array.Sort (O(n))


  • 0
    L
    public class Solution {
        public void NextPermutation(int[] num) {
            int i, j;
            for(i = num.Length - 1; i > 0; i--)
                if(num[i] > num[i-1])
                {
                    int newNum;
                    for(j = i; j < num.Length; j++)
                        if(num[j] <= num[i-1])
                            break;
                    newNum = num[j-1];
                    num[j-1] = num[i-1];
                    num[i-1] = newNum;
                    Array.Sort(num, i, num.Length - i);
                    break;
                }
            if(i == 0) Array.Sort(num);
        }
    }

Log in to reply
 

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