leetcode(31) Next Permutation

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

Implement 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

Subscribe to see which companies asked this question

意思是说求下一个排序,步骤如下:

1.首先从后向前查找nums[]数组中前一个元素小于后一个元素的位置i

2.如果遍历数组到最后,说明数组从后向前依次增大,这时只需要反转数组即可

3.否则从i后面的元素(位置在i+1)开始向后遍历,直到找到某个元素nums[j]小于nums[i],将这两个数交换位置,然后从i+1位置开始到数据最后之间的元素反转即可

java代码:

package leetcode;

public class NextPermutation {

	public static void nextPermutation(int[] nums) {
		if (nums == null || nums.length == 0)
			return;
		int i = nums.length - 2;
		//从后向前遍历直到发现前一个数小于后一个数便记录位置停止循环
		while (i >= 0 && nums[i] >= nums[i + 1]) {
			i--;
		}
		if (i >= 0) {
			int j = i + 1;
			while (j < nums.length && nums[j] > nums[i]) {//找到i位置后面小于i位置的数的index
				j++;
			}
			j--;
			int temp = nums[i];
			nums[i] = nums[j];
			nums[j] = temp;
		}
		reverse(nums, i+1, nums.length - 1);
	}

	/**
	 * 反转数组
	 * 
	 * @param nums
	 *            要反转数组
	 * @param start
	 *            数组开始位置
	 * @param last
	 *            数组结束位置
	 */
	private static void reverse(int[] nums, int start, int last) {
		int l = start;
		int r = last;
		while (l < r) {
			int temp = nums[l];
			nums[l] = nums[r];
			nums[r] = temp;
			l++;
			r--;
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] test = { 1,1,5 };
		System.out.println("before -> ");
		for (int i = 0; i < test.length; i++) {
			System.out.print(test[i] + " ");
		}
		System.out.println("");
		nextPermutation(test);
		System.out.println("after -> ");
		for (int i = 0; i < test.length; i++) {
			System.out.print(test[i] + " ");
		}
		System.out.println("");
	}

}
c++代码:
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;

class Solution{
    public:
        void nextPermutation(vector<int> &nums){
            next_permutation(nums.begin(),nums.end());
        }
        template<typename BidiIt>
        bool next_permutation(BidiIt first,BidiIt last){
            const auto rfirst=reverse_iterator<BidiIt>(last);//反转的第一个即最后一个
            const auto rlast=reverse_iterator<BidiIt>(first);//反转的最后一个即第一个

            auto pivot=next(rfirst);    //最后一个的指针

            //找到前一个小于后一个的编号
            while(pivot!=rlast && *pivot >= *prev(pivot))
                ++pivot;

            if(pivot==rlast){
                reverse(rfirst,rlast);  //如果从最后一个到第一个元素从小到大,则反转整个数组
                return false;
            }

            auto change=find_if(rfirst,pivot,bind1st(less<int>(),*pivot));//找到从rfirst到pivot即pivot到最后一个元素之间第一个小于pivot指向元素的下标
            swap(*change,*pivot);   //交换元素
            reverse(rfirst,pivot);  //反转从pivot到最后一个之间的元素
            return true;
        }
};

int main() {
    vector<int> nums;
    nums.push_back(1);
    nums.push_back(1);
    nums.push_back(5);
    Solution s;
    s.nextPermutation(nums);
    vector<int>::iterator it;
    for(it=nums.begin();it!=nums.end();it++)
            cout<<*it<<" ";
    cout<<endl;
}
注意,用g++编译时g++版本要在4.7以上(由于auto是c++11新特性,4.7版本及以上支持c++11标准),并且要加上-std=c++11参数
如编译上面的代码应输入:
g++ Solution.cpp  -std=c++11 -o Solution




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值