zoukankan      html  css  js  c++  java
  • LeetCode31. 下一个排列

    31. 下一个排列

    实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

    如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。

    必须原地修改,只允许使用额外常数空间。

    以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
    1,2,3 → 1,3,2
    3,2,1 → 1,2,3
    1,1,5 → 1,5,1

    题解

        class Solution {
         public void nextPermutation(int[] nums) {
            if (nums == null || nums.length < 2) {
                return;
            }
            int j = nums.length - 1;
            int flagIndex = nums.length - 1;
            int i =0;
    
            while (j - 1 >= 0 && nums[j - 1] >= nums[j]) {
    
                j--;
                // System.out.println(j);
                flagIndex = j;
    
            }
    
            // System.out.println("25  " + flagIndex);
    
            // 说明有戏
            if (flagIndex > 0) {
                // int min = nums[flagIndex - 1];
                int bigger = nums[flagIndex];
    
                // System.out.println(flagIndex);
    
                int midIndex = flagIndex;
                for (i = flagIndex; i <= nums.length - 1; i++) {
                    if (nums[i] > nums[flagIndex - 1] && nums[i] < bigger) {
                        bigger = nums[i];
                        midIndex = i;
    
                    }
                }
    
                // if (midIndex > 0) {
    
                    swap(nums, midIndex, flagIndex - 1);
                    // print(nums);
    
                    i = midIndex;
                    
                    // 低位排序 有可能 小数插入后,后面有和midIndex相同
                    while (i + 1 < nums.length && nums[i] < nums[i + 1]) {
                        swap(nums, i, i + 1);
    
                        i++;
    
                    // }
    
                }
    
            }
            // System.out.println(flagIndex);
            int high = flagIndex;
            int low = nums.length - 1;
            while (high < low) {
                swap(nums, high, low);
                high++;
                low--;
            }
    
        }
    
        private void swap(int[] nums, int midIndex, int index) {
    
            // int temp = nums[index];
            // nums[index] = nums[midIndex];
            // nums[midIndex] = temp;
            // System.out.println(nums[index] + ", " + nums[midIndex]);
    
            nums[index] = nums[index] ^ nums[midIndex];
            nums[midIndex] = nums[midIndex] ^ nums[index];
            nums[index] = nums[index] ^ nums[midIndex]; 
            // System.out.println(nums[index] + ", " + nums[midIndex]);
    
    
        }
        }
    '''
  • 相关阅读:
    ruby
    快捷键_命令行
    Babylon
    遇见的一些关于js冲突的问题
    js中出生年月日的使用,以及性别的判断
    js中iframe的使用
    js中ul与li的使用
    jQuery,ajax,for循环使用典型案例
    Easy | LeetCode 118. 杨辉三角
    Easy | LeetCode 461. 汉明距离 | 位运算
  • 原文地址:https://www.cnblogs.com/Cyning/p/13705005.html
Copyright © 2011-2022 走看看