31. Next Permutation

栏目: C++ · 发布时间: 5年前

内容简介: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

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

难度:medium

题目:

实现下一个排列数,将数字按词法顺序重新排列为下一个更大的数字置换。如果这样的 排序 不存在,它一定轮转到了最小的那个数。

必须原地置换并且只允许使用常量空间。

思路:参照C++ STL库中实现的next_permutation

Runtime: 8 ms, faster than 98.59% of Java online submissions for Next Permutation.

Memory Usage: 31.2 MB, less than 0.97% of Java online submissions for Next Permutation.

class Solution {
    /**
    * 1. find i <  j (i + 1) from end to start
    * 2. find i < k swap (i, k) from end to start
    * 3. reverse [j, last]
    */
    public void nextPermutation(int[] nums) {
        if (null == nums || nums.length <= 1) {
            return;
        }
        
        int right = nums.length - 1;
        int j = right;
        for (; j > 0; j--){
            if (nums[j - 1] < nums[j]) break;
        }
        for (int k = right; k >= 0; k--) {
            if (j > 0 && nums[k] > nums[j - 1]) {
                swapArray(nums, j - 1, k);
                break;
            }
        }

        for (; j < right; j++, right--) {
            swapArray(nums, j, right);
        }
    }
    
    private void swapArray(int[] a, int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web前端黑客技术揭秘

Web前端黑客技术揭秘

钟晨鸣、徐少培 / 电子工业出版社 / 2013-1 / 59.00元

Web前端的黑客攻防技术是一门非常新颖且有趣的黑客技术,主要包含Web前端安全的跨站脚本(XSS)、跨站请求伪造(CSRF)、界面操作劫持这三大类,涉及的知识点涵盖信任与信任关系、Cookie安全、Flash安全、DOM渲染、字符集、跨域、原生态攻击、高级钓鱼、蠕虫思想等,这些都是研究前端安全的人必备的知识点。本书作者深入剖析了许多经典的攻防技巧,并给出了许多独到的安全见解。 本书适合前端工......一起来看看 《Web前端黑客技术揭秘》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具