Leetcode_next-permutation(c++ and python version)

C++ STL与核心算法精解:华为机试108题实战指南 在算法与数据结构的学习中,掌握高效的工具和核心思想是提升编程能力的关键。C++标准模板库(STL)提供了一套经过高度优化的通用容器和算法,如vector、unordered_map、priority_queue等,能够显著提升开发效率与代码性能。其设计遵循泛型编程思想,通过模板实现类型安全与代码复用,是现代C++工程实践的基石。理解STL各组件的底层原理与适用场景,例如哈希表实现快速查找、堆结构处理优先级问题,对于解决实际编程问题具有重要价值。这些技术广泛应用于系统开发、游戏引擎、高频交易等对性能要求苛刻的 阅读详情

地址:http://oj.leetcode.com/problems/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

思路:在讲思路前插个曲。晚上听了大部分worldquant的兼职招聘的宣讲后提前退场回实验室刷题了,但是发现Leetcode挂了,还挂了很久,至少一个半小时,虽然之前遇到好几次leetcode挂了的现象,但是基本几分钟十几分钟就好了。所以无意间发现了这个:

http://www.keithschwarz.com/interesting/code/?dir=next-permutation

正好是此题。

大意是:

1. 从数组尾向头找到最大连续升序的序列 x

2. 将序列x起点(数组尾为终点)左边的数(如果有的话),记为y,与该序列中大于y的最小的数交换

3. 将交换后的序列x排序(从小到大)

c++参考代码:

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        if(num.empty())
            return;
        int pos = num.size()-1;
        while(pos && num[pos]<=num[pos-1])
            --pos;
        if(!pos)
            sort(num.begin(), num.end());
        else
        {
            for(int i = num.size()-1; i>=pos; --i)
                if(num[i] > num[pos-1])
                {
                    swap(num[i], num[pos-1]);
                    break;
                }
            sort(num.begin()+pos, num.end());
        }
    }
};

python参考代码:

class Solution:
    # @param num, a list of integer
    # @return a list of integer
    def nextPermutation(self, num):
        if not num:
            return num
        for i in range(len(num)-1,0,-1):
            if num[i] > num[i-1]:
                for j in range(len(num)-1,i-1,-1):
                    if num[j] > num[i-1]:
                        num[i-1], num[j] = num[j], num[i-1]
                        break
                return num[:i] + sorted(num[i:])
        return sorted(num)

 
//what's more, it can also abandon sorting at last. What's amazing is the code below is 20ms+ later than the upper one.
//I think there must be some optimizations in STL.
//coding two weeks later.

class Solution {
public :
     void nextPermutation ( vector < int > & num ) {
         if ( num . empty () || num . size () == 1 )
             return ;
         int pos = num . size () - 1 ;
         for (; pos >= 1 ; -- pos )
         {
             if ( num [ pos ] > num [ pos - 1 ])
                 break ;
         }
         if ( ! pos )
         {
             for ( int i = 0 , j = num . size () - 1 ; i < j ; ++ i , -- j )
                 swap ( num [ i ], num [ j ]);
         }
         else
         {
             for ( int i = num . size () - 1 ; i >= pos ; -- i )
             {
                 if ( num [ i ] > num [ pos - 1 ])
                 {
                     swap ( num [ i ], num [ pos - 1 ]);
                     break ;
                 }
             }
             for ( int j = num . size () - 1 ; j > pos ; -- j , ++ pos )
                 swap ( num [ j ], num [ pos ]);
             return ;
         }
     }
};


 
//Thrid trial
class Solution {
public :
     void nextPermutation ( vector < int > & num ) {
         if ( num . empty ())
             return ;
         int sz = num . size (), pos = 0 ;
         for ( pos = sz - 1 ; pos >= 1 ; -- pos )
         {
             if ( num [ pos ] > num [ pos - 1 ])
                 break ;
         }
         if ( ! pos )
             reverse ( num . begin (), num . end ());
         else
         {
             for ( int i = sz - 1 ; i >= pos ; -- i )
             {
                 if ( num [ i ] > num [ pos - 1 ])
                 {
                     swap ( num [ i ], num [ pos - 1 ]);
                     break ;
                 }
             }
             reverse ( num . begin () + pos , num . end ());
         }
     }
};

国央企创新负责人如何通过平台实现科研成果的快速识别与转化?.docx 科易网基于AI模型+行业大数据,在技术转移、成果转化、技术经纪、知识产权、产业创新、科技招商等垂直领域的多样化应用场景,推出科技创新领域的AI+工具与数智化解决方案,推动科技创新与产业创新智能化发展。 立即下载

相关推荐

DrMOS电路仿真

将驱动电路与功率MOS集成化后既是DrMOS。把驱动芯片以及上下桥MOSFET封装在一起,这样每一相供电就有了单独的驱动芯片,并且这种高度整合的MOSFET可以通过更高的电流、发热比传统的MOSFET也小很多且更节能 自举升压同步BUCK高低侧栅驱动电路原理及仿真 ...

Srambler的博客 5039

C/C++刷题环境搭建与STL实战:从零掌握算法底层实现

算法是计算机科学的核心基础,其本质是通过特定步骤高效解决计算问题。理解算法的时间与空间复杂度,关键在于掌握数据在内存中的组织与访问方式。C/C++语言因其贴近硬件、内存管理透明的特性,成为深入理解算法底层原理的理想工具。通过手动管理内存、操作指针,开发者能直观感知数据结构的扩容、拷贝开销,从而建立对算法性能的深刻认知。在工程实践中,标准模板库(STL)提供了vector、unordered_map等高效容器,配合sort、binary_search等泛型算法,能极大提升开发效率。本文以LeetCode算法训

weixin_30423977的博客 351

Windows下Delft3D安装全攻略:从申请许可到编译运行(避坑指南)

本文详细解析了Windows系统下Delft3D的完整安装流程,涵盖环境准备、许可获取、源码编译到性能调优的全过程。针对中国用户常见的网络问题和系统兼容性痛点,提供了经过验证的解决方案,特别强调Intel Fortran编译器匹配、环境变量配置等关键步骤,帮助水利工程师高效完成这一水动力学模拟工具的部署。

weixin_28736355的博客 548

算法竞赛入门指南:从C++环境搭建到核心思维训练

算法是计算机科学的核心,它通过一系列指令解决特定问题,其效率直接影响程序的性能。理解算法的时间与空间复杂度是评估解决方案可行性的基础,这涉及到对数据结构(如数组、链表、树)和经典算法(如排序、搜索)的掌握。在工程实践中,高效算法能显著提升软件处理海量数据的能力,广泛应用于搜索引擎、推荐系统、路径规划等场景。对于希望快速上手算法实践的开发者而言,算法竞赛提供了一个绝佳的练兵场。本文聚焦于C++语言在竞赛中的高效应用,详细介绍了如何配置轻量级的VSCode与MinGW开发环境,并深入讲解了STL容器(如vect

weixin_30274627的博客 404

从Oracle到腾讯TDSQL数据库升级技术分享

腾讯TDSQL(Tencent Distributed SQL)是一款兼具关系数据库和NoSQL数据库优点的新型数据库,文章主要分享oracle升级为TDSQl数据库技术经验。

u012372850的专栏 2613

# 芯片良率是怎么算出来的?——从泊松到负二项分布,一个芯片测试工程师的视角

- 良率=好Die/总Die,但选错模型可能差17个百分点 - Poisson模型过于悲观,Murphy居中,**Negative Binomial才是业界标配** - 关键不是良率数字,是**跟踪聚类因子α的变化**——它能早几周预警工艺漂移 - Chiplet时代,10颗90%良率的Die封在一起,整体良率只有35%

Freezeblur的博客 652

信奥P13713“晴天”题解:C++算法实现与周期问题抽象

在计算机算法与编程竞赛中,周期性问题是一个基础且重要的概念,它广泛存在于日程安排、资源调度和状态模拟等应用场景。其核心原理是利用取模运算,将无限延伸的时间线映射到一个有限的循环内,从而实现高效的状态查询与预测。掌握这一原理,对于提升算法抽象能力和代码实现效率具有显著价值。本文以信息学奥林匹克竞赛(信奥)中的一道典型题目“晴天”为例,深入探讨了如何将生活化场景抽象为周期判断的数学模型,并详细对比了数组标记法、集合查找法以及排序结合二分查找等多种C++实现方案。通过结合**C++** 的高效特性和**STL(标

weixin_30751947的博客 426

金蝶ERP元数据解析:字段属性与表结构映射实战

本文深入解析金蝶ERP元数据的核心价值与应用实践,详细介绍了字段属性与表结构映射的关键技术。通过缓存获取与工具类直连两种方案对比,结合实际案例展示元数据在数据库校验、动态表单生成等场景的应用,帮助开发者高效解决二次开发中的常见问题。

weixin_33738555的博客 433

What is the difference between new and malloc()?

我记不得我曾多少次在网上搜索new 和 malloc 的区别,qian

x 1196

Qt图形几何之QRect详解:从基础操作到高级功能全解析

本文全面介绍了Qt框架中的QRect类,详细解析了其核心功能和使用方法。主要内容包括:1)QRect的基本概念与多种构造函数;2)矩形属性获取和状态判断方法;3)几何操作函数(移动、调整大小等);4)几何关系判断(包含、相交等);5)坐标变换和边距处理;6)实用功能与QRectF转换;7)综合应用示例(图形界面、碰撞检测、布局管理);8)性能优化建议和常见陷阱。通过丰富的代码示例,展示了QRect在Qt图形编程中的实际应用,帮助开发者掌握矩形处理的各项操作技巧,提升图形界面开发效率。

专注现代C++实战,从核心语法到高性能编程,助力开发者深入掌握系统级编程精髓。 117

【温室气体】GOSAT 数据产品

【温室气体】GOSAT 数据产品

WW、forever的博客 238

Leetcode_word-break(c++ and python version)

地址:http://oj.leetcode.com/problems/word-break/

x 1048

全球首发48V架构的Cybertruck,到底牛在哪?| 深扒特斯拉高压系统架构

特斯拉Cybertruck作为全球首款标配48V架构的量产车,在电气系统架构上进行了多项创新。首先,它采用以太网连接高压控制器与后域控制器,提升了数据传输效率和智能化水平。其次,Cybertruck引入了Pyro烟火断开装置,用于碰撞时快速断开电池连接,提高安全性。在电流监测方面,特斯拉既保留了传统的Shunt分流器技术,又引入了更先进的磁通门电流传感器,后者具有无温漂、完全隔离等优势。48V供电系统在降低电流损耗方面表现优异,但也面临电弧风险、盐水腐蚀等挑战。Cybertruck的48V系统通过PCS供电

weixin_43199439的博客 1347

PAT 3-05. 求链式线性表的倒数第K项

题目地址:http://pat.zju.edu.cn/contests/ds/3-05 用vector有一个case超时,用list 顺利通过 #include #include using namespace std; int main() { int K, num; list vec; scanf("%d", &K); while(sc

x 988

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

**Leetcode_median-of-two-sorted-arrays (c++ and python version)

地址:http://oj.leetcode.com/problems/median-of-two-sorted-arrays/ There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time comp

x 976

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

Leetcode_length-of-last-word (updated c++ and python version)

地址:http://oj.leetcode.com/problems/length-of-last-word/ Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If th

x 967

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

**Leetcode_copy-list-with-random-pointer (c++ and python version)

地址:http://oj.leetcode.com/problems/copy-list-with-random-pointer/ A linked list is given such that each node contains an additional random pointer which could point to any node in the list or nul

x 958

Leetcode_populating-next-right-pointers-in-each-node-ii(updated c++ version)

地址:http://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/

x 947

**Leetcode_largest-rectangle-in-histogram(c++ and python version)

地址:http://oj.leetcode.com/problems/largest-rectangle-in-histogram/

x 944

Leetcode_search-in-rotated-sorted-array-ii(updated c++ and python version)

地址:http://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/ Follow up for "Search in Rotated Sorted Array": What if duplicates are allowed? Would this affect the run-time complexity

x 878

Leetcode_wildcard-matching(c++ and python version)

地址:http://oj.leetcode.com/problems/wildcard-matching/

x 869

Leetcode_binary-tree-zigzag-level-order-traversal (updated c++ and python version)

地址:http://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right

x 837

Leetcode_two-sum (c++ and python version)

地址:http://oj.leetcode.com/problems/two-sum/ Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two

x 808

Leetcode_remove-duplicates-from-sorted-array-ii (c++ and python version)

地址:http://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted arra

x 806

*Leetcode_binary-tree-maximum-path-sum (updated c++ and python version)

地址:http://oj.leetcode.com/problems/binary-tree-maximum-path-sum/ Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example: Given the be

x 788

Leetcode_best-time-to-buy-and-sell-stock-ii(c++ and python version)

地址: http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the

x 775
上一篇: Leetcode_permutation-sequence(c++ and python version)
下一篇: Leetcode_search-in-rotated-sorted-array-ii(updated c++ and python version)
fibo_nacci
博客等级 码龄18年 21粉丝 239原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值