12ms c++ Solution


  • 0
    C
    //Next Permutation
    class Solution {
    public:
    void nextPermutation(vector<int>& nums) {
    	
    	int n = nums.size();
    	if (n == 1)
    		return;
    	int i = n - 1;
    	for (i = n - 1; i >= 1; i--)
    	{
    		if (nums[i] > nums[i - 1])
    			break;
    	}
    	i--;
    	//n-1到i+1找一个比i大的,或者i-1往前找一个比i小的替换
    	if (i < 0)
    	{
    		reverse(nums.begin(), nums.end());
    		return;
    	};
    	for (int j = n - 1; j >= i+1; j--)
    	{
    		if (nums[j] > nums[i])
    		{
    			swap(nums[j], nums[i]);
    			sort(nums.begin() + i + 1, nums.end());
    			return;
    		}
    	}
    	for (int j = i - 1; j >= 0; j--)
    	{
    		if (nums[j] > nums[i])
    		{
    			swap(nums[j], nums[i]);
    			sort(nums.begin() + i + 1, nums.end());
    			return;
    		}
    	}
    }
    };

Log in to reply
 

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