• [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]

  • 相关阅读:
    loadrunner实现字符串的替换
    Windows Server 2008 R2 实现多用户同时登陆
    LoadRunner测试场景中添加负载生成器
    loadrunner统计字符串中指定字符出现的次数
    loadrunner怎么将变量保存到参数中
    loadrunner生成随机数
    loadrunner取出字符串的后面几位
    loadrunner参数化excel数据
    LoadRunner常用函数列表
    loadrunner解决在项目中的难点解决
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078983.html
Copyright © 2020-2023  润新知