• 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

    首先要明白什么是next permutation. 

     转leetcode solution : 

    (1) 在当前序列中,从尾端往前寻找到第一对两个相邻元素,前一个记为first,后一个记为second,这对元素满足first 小于 second。

    (2) 然后再从尾端寻找另一个元素number,如果满足first 小于number,即将第first个元素与number元素对调,并将second元素之后(包括second)的所有元素颠倒排序,即求出下一个序列

    example:
    6,3,4,9,8,7,1
    此时 first = 4,second = 9
    从尾到前找到第一个大于first的数字,就是7
    交换4和7,即上面的swap函数,此时序列变成6,3,7,9,8,4,1
    再将second=9以及以后的序列重新排序,让其从小到大排序,使得整体最小,即reverse一下(因为此时肯定是递减序列
    得到最终的结果:6,3,7,1,4,8,9

    public class Solution {
        /* 
        (1) 从后往前,找到第一个nums[i] < nums[i+1]的i
        (2) 从 nums[length -1]开始往i + 1 开始找,找到第一个大于nums[i]的数,交换之
        (3) 将nums[i+1 ~ length - 1] 的数reverse
        */
        public void nextPermutation(int[] nums) {
            if(nums == null || nums.length <= 1) {
                return;
            }
            
            int length = nums.length - 1;
            
            int i = length;
            for(; i >= 1; i--) {
                if(nums[i - 1] < nums[i]) {
                    break;
                }
            }
            
            if(i != 0) {
                swap(nums, i - 1);
            }
                
            reverse(nums, i, length);
        
        }
        
        public void swap(int[] nums, int i) {
            
            for(int j = nums.length - 1; j > i; j--) {
                if(nums[j] > nums[i]) {
                    swap(nums, i, j);
                    break;
                }
            }
        }
        
        public void swap(int[] nums, int i, int j) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
        
        public void reverse(int[] nums, int i, int j) {
            while(i < j) {
                swap(nums, i , j);
                j--;
                i++;
            }
        }
    }
    

      

  • 相关阅读:
    css3动画之1--animation小例子
    炎炎夏日,走入美妙的前端设计案例
    模拟腾讯、携程、百度音乐 移动端图片切换第一版
    仿QQ空间长图效果简易版--母亲节感恩
    001-搭建框架
    javascript事件绑定1-模拟jquery可爱的东西
    图片尺寸
    mvc3结合spring.net-依赖注入
    *创建索引初步
    Lucene的分词_中文分词器介绍
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6406006.html
Copyright © 2020-2023  润新知