leetcode--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


题意:给定一个全排列,求下一组全排列。

分类:数组


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

[java]  view plain  copy
  1. public class Solution {  
  2.     public void nextPermutation(int[] nums) {  
  3.         if(nums.length<=1return;  
  4.         int i = nums.length-1;  
  5.         while(i>0){//倒序找到第一对逆序数  
  6.             if(nums[i]>nums[i-1]){  
  7.                 break;  
  8.             }  
  9.             i--;  
  10.         }  
  11.         if(i>0){//找到逆序对  
  12.              int j = nums.length-1;  
  13.              i--;//指向逆序对的第一个元素  
  14.              while(j>=0){//找到大于nums[i]的第一个元素  
  15.                 if(nums[j]>nums[i]){  
  16.                     break;  
  17.                 }  
  18.                 j--;  
  19.              }    
  20.              int temp =  0;//交换i,j  
  21.              temp = nums[i];  
  22.              nums[i]= nums[j];  
  23.              nums[j] = temp;  
  24.              reverse(nums, i+1, nums.length-1);//翻转  
  25.         }else{//没有找到逆序对  
  26.             reverse(nums, 0, nums.length-1);  
  27.         }            
  28.         System.out.println(Arrays.toString(nums));  
  29.     }  
  30.      
  31.     public void reverse(int[] nums,int low,int high){  
  32.         int temp = 0;  
  33.         while(low<high){  
  34.             temp = nums[low];  
  35.             nums[low] = nums[high];  
  36.             nums[high] = temp;  
  37.             low++;high--;  
  38.         }  
  39.     }  
  40. }  

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/45619211

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值