leetcode 31

来源:互联网 发布:贪吃蛇大作战 算法 编辑:程序博客网 时间:2024/06/01 15:00

【题目】

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

即找出一串数字的字典序排序的下一个序列

【思路】

实现了C++中stl::next_permutation的思路,即

在当前序列中,从尾端往前寻找两个相邻元素,前一个记为*i,后一个记为*ii,并且满足*i < *ii。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第ii个元素之后(包括ii)的所有元素颠倒排序,即求出下一个序列

【Java代码】

public void nextPermutation(int[] nums){if(nums.length >1){int i = nums.length-2,ii = nums.length-1,j = ii;boolean flag = false;while(i >= 0)if(nums[i] < nums[ii]){flag = true;break;}else{i--; ii--;}if(flag){while(j >= 0)if(nums[j] > nums[i])break;elsej--;    int temp = nums[i];    nums[i] = nums[j];    nums[j] = temp;}else{ii = 0;}for(int start = ii,end = nums.length-1 ; start < end; start++,end--){int temp = nums[start];nums[start] = nums[end];nums[end] = temp;}}}


原创粉丝点击