zoukankan      html  css  js  c++  java
  • [LeetCode] 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
    » Solve this problem

    [解题思路]
    这题更像一道数学题,画了个图表示算法,如下:


    [Code]
    1:      void nextPermutation(vector<int> &num) {   
    2: // Start typing your C/C++ solution below
    3: // DO NOT write int main() function
    4: assert(num.size() >0);
    5: int vioIndex = num.size() -1;
    6: while(vioIndex >0)
    7: {
    8: if(num[vioIndex-1] < num[vioIndex])
    9: break;
    10: vioIndex --;
    11: }
    12: if(vioIndex >0)
    13: {
    14: vioIndex--;
    15: int rightIndex = num.size()-1;
    16: while(rightIndex >=0 && num[rightIndex] <= num[vioIndex])
    17: {
    18: rightIndex --;
    19: }
    20: int swap = num[vioIndex];
    21: num[vioIndex] = num[rightIndex];
    22: num[rightIndex] = swap;
    23: vioIndex++;
    24: }
    25: int end= num.size()-1;
    26: while(end > vioIndex)
    27: {
    28: int swap = num[vioIndex];
    29: num[vioIndex] = num[end];
    30: num[end] = swap;
    31: end--;
    32: vioIndex++;
    33: }
    34: }

    [已犯错误]
    1. Line 16
    要找的是右边第一个大于violate number的值,而不是等于。如果代码写成
    while(rightIndex >=0 && num[rightIndex] < num[vioIndex]) 
    那么在处理[1,5,1]时,会返回[1,1,5],而不是[5,1,1]

  • 相关阅读:
    单线程的JavaScript是如何实现异步的
    前端优化之 -- 使用 require.context 让项目实现路由自动导入
    插入排序
    选择排序
    冒泡排序
    强缓存和协商缓存
    ES6 Set求两个数组的并集、交集、差集;以及对数组去重
    实现一个new操作符
    我理解的浅拷贝和深拷贝
    javascript专题系列--js乱序
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078983.html
Copyright © 2011-2022 走看看