美文网首页Leetcode
Leetcode 31. Next Permutation

Leetcode 31. Next Permutation

作者: SnailTyan | 来源:发表于2018-08-31 19:20 被阅读12次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Next Permutation

    2. Solution

    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int index = -1;
            int min = 0;
            for(int i = nums.size() - 1; i > 0; i--) {
                if(nums[i] > nums[i - 1] ) {
                    index = i - 1;
                    min = i;
                    break;
                }
            }
            if(index == -1) {
                return reverse(nums.begin(), nums.end());
            }
            for(int i = index + 1; i < nums.size(); i++) {
                if(nums[i] > nums[index] && nums[i] < nums[min]) {
                    min = i;
                }
            }
            swap(nums[index], nums[min]);
            sort(nums.begin() + index + 1, nums.end());
        }
        
    private:
        void swap(int& a, int& b) {
            int temp = a;
            a = b;
            b = temp;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/next-permutation/description/

    相关文章

      网友评论

        本文标题:Leetcode 31. Next Permutation

        本文链接:https://www.haomeiwen.com/subject/zwsewftx.html