zoukankan      html  css  js  c++  java
  • 31-Next Premutation

    【题目】

    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

    【analyze】

    1.从后往前找(找到第一个元素的值比后序的元素值 小,索引记为pivot)

    2.再从后往前找(找到第一个元素的值比pivot处的元素大的值(不要=),索引记为large),交换pivot和large

    3.将pivot+1-end之间的元素逆转

    【算法】

    public class Solution {
        public void nextPermutation(int[] nums) {
            int len=nums.length;
            int pivot=len-1;
            while(pivot>0) {
                if(nums[pivot]>nums[pivot-1])
                    break;
                pivot--;
            }
            if(pivot>0) {
                pivot--;
                int large=len-1;
                while(nums[pivot]>=nums[large])   //找出比pivot元素值大的large
                    large--;
                swap(nums,pivot,large);
                reverse(nums,pivot+1,len-1);
            }else {
                reverse(nums,0,len-1);
            }
        }
        //将数据区间的元素逆转
        public void reverse(int[] nums,int first,int end) {
            for(int i=0;i<(end-first+1)/2;i++) {
                swap(nums,first+i,end-i);
            }
        }
        //交换元素
        public void swap(int[] nums,int a,int b) {
            int temp=nums[a];
            nums[a]=nums[b];
            nums[b]=temp;
        }
    }
  • 相关阅读:
    SQL SERVER数据库优化相关资料
    京东面试题
    Jenkins部署资料
    [POI2005]Bank notes 【多重背包】
    [Usaco2004Feb]Cow Marathon 树的直径
    [ZJOI2008]骑士 基环树
    种树 反悔操作 【贪心】
    Poj2442 Sequence 贪心+堆优化
    洛谷div2【XR-4】歌唱比赛
    洛谷div2【XR-4】模拟赛
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4483064.html
Copyright © 2011-2022 走看看