48_leetcode_Next Permutation

来源:互联网 发布:js继承题目 编辑:程序博客网 时间:2024/05/07 17:38

mplement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1


1:特殊情况, size <= 1;2:从后到前遍历数组, 比较当前数字大小与前一个数字的大小,如果当前数字小,则向前移动;3:如果不存在后一个数字大于前一个数字,则直接排序数组,并返回;4:找到相应的索引,替换数字,并对数组后面的部分进行排序。



  void nextPermutation(vector<int>& num)    {        if(num.size() <= 1)        {            return;        }                int curIndex = (int)num.size() - 1;                for(; curIndex >= 1; curIndex--)        {            if(num[curIndex] > num[curIndex - 1])                break;        }                //从后到后非降序排列        if(curIndex == 0)        {            sort(num.begin(), num.end());            return;        }            int lastIndex = curIndex - 1;        int minIndex = curIndex;        int minNumber = num[curIndex];                for(int i = curIndex + 1; i < (int)num.size(); i++)        {            if(num[i] > num[lastIndex] && num[i] < minNumber)            {                minNumber = num[i];                minIndex = i;            }        }                swap(num[lastIndex], num[minIndex]);        sort(num.begin() + lastIndex + 1, num.end());        return;    }


0 0
原创粉丝点击