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 }
  • 相关阅读:
    排序规则
    revert
    添加字段modify
    修改字段名change
    修改字段注释modify
    修改字段类型modify
    file类型input框赋值
    disabled
    js失去焦点触发
    别把软件开发当做养家糊口的工具...
  • 原文地址:https://www.cnblogs.com/hyxsolitude/p/12308487.html
Copyright © 2011-2022 走看看