zoukankan      html  css  js  c++  java
  • 31. 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 and use only constant 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 class Solution {
     2     public int find(int []nums, int v, int l1, int r1) {
     3         for (int i = l1; i <= r1; ++i) {
     4             if (nums[i] > v) return i;
     5         }
     6         return 0;
     7     }
     8     public void nextPermutation(int[] nums) {
     9         int n = nums.length;
    10         
    11         int i = n - 1;
    12         
    13        
    14         while (i - 1 >= 0 && nums[i] <= nums[i - 1]){
    15             i--;
    16         }
    17           
    18         
    19         if (i == 0) {
    20             Arrays.sort(nums);
    21         } else {
    22             Arrays.sort(nums, i, n);
    23             int id = find(nums, nums[i - 1], i, n - 1);
    24             int temp = nums[id];
    25             nums[id] = nums[i - 1];
    26             nums[i - 1] = temp;
    27         }
    28         
    29         
    30     }
    31 }
  • 相关阅读:
    软件设计中的立足点
    Clojure基础
    团队凝聚力
    执行力与领导力
    工作与生活
    分离焦虑OR责任焦虑
    保持激情
    立足点
    论研发管理--开篇
    初级码农常犯错误
  • 原文地址:https://www.cnblogs.com/hyxsolitude/p/12308487.html
Copyright © 2011-2022 走看看