zoukankan      html  css  js  c++  java
  • [LeetCode-JAVA] 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, 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

    题意:找到下一个排列数

    思路:主要就是根据经验,要记住这个找排列数的规律

    (1) 首先从后往前找到第一个下降的位置,记为i,如果没有则证明是最后一个排序,下一个为原串的逆序

    (2) 从i往后,找到比i对应的数值大的当中最小的对应的index(由于后面都是降序的,所以找到第一个小于等于i对应的数值的前一个即为所求),如果没有则为length-1;

    注: (例如 2,3,6,5,4,1  第一个降序的为3 比3大的当中 最小的为4)

    (3) 交换nums[i] 和 nums[index] 

    (4) 将i后面的逆序

    代码:

    public class Solution {
        public void nextPermutation(int[] nums) {
            if(nums.length < 2)
                return;
            for(int i = nums.length - 2 ; i >= 0 ; i--) {
                if(nums[i] < nums[i+1]) {
                   int index = nums.length - 1;
                   for(int j = i + 1 ; j < nums.length ; j++) { // 找到比nums[index]大的当中最小的
                       if(nums[j] <= nums[i]){  //一定要有等号哦
                           index = j - 1;
                           break;
                       }
                   }
                   int temp = nums[i];
                   nums[i] = nums[index];
                   nums[index] = temp;
                   
                   reverse(nums, i+1, nums.length-1);
                   return;
                }
            }
            
            reverse(nums, 0, nums.length-1);
            return;
        }
        
        public void reverse(int[] nums, int begin, int end) {
            if(begin == end)
                return;
            
            while(begin < end) {
                int temp = nums[begin];
                nums[begin] = nums[end];
                nums[end] = temp;
                begin++;
                end--;
            }
        } 
    }
  • 相关阅读:
    .net core 操作域控 活动目录 ladp -- Support for System.DirectoryServices for Windows
    运行在 Android 系统上的完整 Linux -- Termux
    Windows Python 版本切换工具 --- Switch Python Version Tool For Windows
    简单的NLog配置文件
    python之set基本使用
    复习PHP的数组
    php动态修改配置文件
    制作一个php万年历
    一个简单的选项卡
    python操作文件的笔记
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4699549.html
Copyright © 2011-2022 走看看