首页 > 其他 > 详细

Next Permutation

时间:2015-08-12 11:31:11      阅读:118      评论:0      收藏:0      [点我收藏+]

ARRAY;

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

,抓住题目意思,正常是升序,升序之后渐渐的在后面降序,

首先找到::  需要交换的元素i,j。然后交换。 之后进行reverse。

其中::1,2,3.最后一个升序的,2,3将其交换就好

如 其他的,抓住最后一个升序的, 

  最后一个升序的小技巧,找到比后面小的数,然后找到最后一个大的数字。

class Solution {
public:
  	void reversePart(vector<int>& nums,int k)
	{
		int j=nums.size()-1;
	    int i=k+1;
		while(i<=j)
		{
			swap(nums[i],nums[j]);
           i++;
		   j--;			
		}
	}
	void nextPermutation(vector<int>& nums)
	{
		int flag=0;
		if(nums.size()==1)
			return;
		//find j
		int i=nums.size()-1;
		while (i>0&&nums[i-1]>=nums[i])//after is bigger.
		{
			i--;
		}
		int j=i;
		//difficult for me.
		while(j<nums.size()&&nums[j]>nums[i-1])j++;
		if(i==0)
			reversePart(nums,-1);
		else
		{
			swap(nums[i-1],nums[j-1]);
			reversePart(nums,i-1);
		}
	}
};

如有不对的地方,请指正!

版权声明:本文为博主原创文章,未经博主允许不得转载。

Next Permutation

原文:http://blog.csdn.net/q286989429/article/details/47441481

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!