【LeetCode】12.Next Permutation

题目描述(Medium)

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 and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

题目链接

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

Example 1:

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

算法分析

1. 逆序查找,找到第一个非逆序递增的数字pivot;

2. 逆序查找,找到第一个大于pivot的数字;

3. 交换两个数字;

4. pivot右边的数字逆序。

提交代码:

class Solution {
public:
	void nextPermutation(vector<int>& nums) {
		// 1.逆序查找,找到第一个非逆序递增的数字;
		auto rfirst = nums.rbegin();
		auto rlast = nums.rend();
		auto pivot = rfirst + 1;

		while (pivot != rlast && *pivot > *(pivot - 1))
			++pivot;

		if (pivot == rlast)
		{
			reverse(rfirst, rlast);
			return;
		}

		// 2.逆序查找,找到第一个大于pivot的数字
		// bind1st, *pivot作为<左边(第一个参数)
		auto onchange = find_if(rfirst, pivot, bind1st(less<int>(), *pivot));

		// 3.交换两个数字
		swap(*pivot, *onchange);

		// 4.pivot右边的数字逆序
		reverse(rfirst, pivot);
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, vector<int>& nums, vector<int>& expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	s.nextPermutation(nums);

	if (nums == expected)
		printf("passed\n");
	else
		printf("failed\n");

}

int main(int argc, char* argv[])
{

	vector<int> array1 = { 1, 2, 3 };
	vector<int> excepted = { 1, 3, 2 };
	Test("Test1", array1, excepted);

	array1 = { 3, 2, 1 };
	excepted = { 1, 2, 3 };
	Test("Test2", array1, excepted);

	array1 = { 1, 1, 5 };
	excepted = { 1, 5, 1 };
	Test("Test2", array1, excepted);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82017171
今日推荐