zoukankan      html  css  js  c++  java
  • LintCode-Previous Permuation

    Given a list of integers, which denote a permutation.

    Find the previous permutation in ascending order.

    Note

    The list may contains duplicate integers.

    Example

    For [1,3,2,3], the previous permutation is [1,2,3,3]

    For [1,2,3,4], the previous permutation is [4,3,2,1]

    Analysis:

    Find out the fisrt local minimum and add it and its later elements into a list from back to front. Add the element just before this minimum into list also, set the element as bar ( we will decrease it to some smaller value). Sort the list, find out the next value smaller than the bar, put it on the position that one before the local minimum, then put all left elements in the list to the array in the decreasing order.

    Solution:

     1 public class Solution {
     2     /**
     3      * @param nums: A list of integers
     4      * @return: A list of integers that's previous permuation
     5      */
     6     public ArrayList<Integer> previousPermuation(ArrayList<Integer> nums) {
     7         int len = nums.size();
     8         if (len==0 || len ==1) return nums;
     9 
    10         ArrayList<Integer> buff = new ArrayList<Integer>();
    11         buff.add(nums.get(len-1));
    12         int index = len-2;
    13         while (index>=0 && nums.get(index)<= nums.get(index+1)){
    14             buff.add(nums.get(index));
    15             index--;
    16         }
    17         
    18         if (index>=0){
    19             buff.add(nums.get(index));
    20             int bar = nums.get(index);
    21             Collections.sort(buff);
    22             int index2 = buff.size()-2;
    23             while (!(buff.get(index2)!=bar && buff.get(index2+1)==bar)) index2--;
    24             nums.set(index,buff.get(index2));
    25             buff.remove(index2);
    26             index++;
    27             for (int i=buff.size()-1;i>=0;i--){
    28                 nums.set(index,buff.get(i));
    29                 index++;
    30             }
    31             return nums;
    32         } else {
    33             Collections.sort(buff, Collections.reverseOrder());
    34             return buff;
    35         }    
    36     }
    37 }
  • 相关阅读:
    SharePoint学习资料收集
    VS2008 IDE界面
    罗列没有主键的表
    Google Calendar API练习
    pb中数据窗口中字段只显示255个的解决方法
    oracle 中的事务和update from 语句
    sqlserver2005数据库扩容方案
    在一个表上创建非聚集索引和聚集索引
    <xsl:applytemplates/>的应用
    时间戳转换为日期类型
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4191079.html
Copyright © 2011-2022 走看看