leetcode 旋转链表 python

Leetcode 061 旋转链表 python (多解法) 一步一个脚印的python leetcode 题解。本人一直在努力地积累Leetcode上用Python实现的题,并且会尽力讲清每道题的原理,绝不像其他某些博客简略地带过。 如果觉得讲的清楚,欢迎关注。   题目描述: 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NUL... 阅读详情

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

示例 1:

输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL

示例 2:

输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL

本题有两种情况一种是k小于这个链表的大小时,就是示例1,另一种是k大于链表的大小时例如示例2.

思路:采用双指针的方法,一个快指针fast一个慢指针slow,然后fast先开始走当快指针走了k步时慢指针开始走,当fast指向None时,slow指向要旋转的节点,然后将slow与slow断开即可。其中k>size时链表旋转的位置就等于k%size,所以我们令k=k%size

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if head==None:
            return head
        if head.next == None:
            return head
        fast = head
        slow = head
        p = head
        newHead = None
        count = 1
        while p.next!=None:
            p = p.next
            count += 1
        k = k % count
        while fast.next!=None:
            fast = fast.next
            if k<=0:
                slow = slow.next
            k -= 1
        fast.next = head
        newHead = slow.next
        slow.next = None
        return newHead

 

leetcode—python 50天刷题 第21题 旋转链表 题目描述 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4->NULL 向右旋转 2 步: 4->5->1->2->3->NULL 示例 2: 输入: 0->1->2-& 阅读详情

相关推荐

Vivado Schematic视图实战:从RTL分析到布局布线,如何用它快速定位设计问题(附2019.1版操作)

本文深入解析Vivado Schematic视图在FPGA设计中的关键作用,从RTL分析到布局布线全流程,帮助工程师快速定位设计问题。通过三重视图对比、高效调试四步法和高级技巧,提升问题排查效率,缩短调试时间。文章结合2019.1版操作指南和实战案例,展示如何利用Schematic视图解决典型设计问题。

weixin_30591551的博客 495

旋转链表(数据结构基础回顾)

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4->NULL 向右旋转 2 步: 4->5->1->2->3->NULL 示例 2: 输入: 0->1->2-&g

ambiguous__的博客 4152

QT5.14.2+VS2019安装配置教程Windows

QT5.14.2+VS2019安装使用教程Windows前言一. QT的下载与安装1. QT的下载2. QT的安装二. 配置Visual Studio编译器环境1. 扩展工具下载2. 扩展工具配置 前言 由于Visual Studio 的功能强大,很多开发人员比较熟悉使用,所以可以通过将QT配置到Visual Studio中进行开发。 一. QT的下载与安装 1. QT的下载 QT5.14.2下载地址 2. QT的安装 断开网络!断开网络!!断开网络!!! 安装QT之前,需要断开电脑的网络连接,这样就

Zander0的博客 7262

旋转链表

1. 问题描述: 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4->NULL 向右旋转 2 步:...

weixin_44470078的博客 279

WorldQuant Brain Alpha 生成器

一个自动化工具,通过参数优化和回测来挖掘高质量的量化交易 Alpha 因子,并自动提交符合标准的因子。

weixin_37582383的博客 1万+

用PyTorch复现经典:手把手教你用Double DQN训练AI玩转打砖块(附完整代码与调参心得)

本文详细介绍了如何使用PyTorch实现Double DQN算法,训练AI智能体玩转经典雅达利游戏Breakout(打砖块)。从环境配置、帧预处理到网络架构设计和经验回放机制,全面解析了强化学习在游戏AI中的应用。文章还提供了关键调参技巧和实战优化方案,帮助开发者快速掌握Double DQN的核心实现与性能优化方法。

weixin_30596165的博客 231

Java,LeetCode 61. 旋转链表

链表,旋转链表 1. 题目描述 难易度:中等 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4->NULL 向右旋转 2 步: 4->5->1->2->3->NULL 示例 2: 输

!不将就的博客 375

OrCAD Capture CIS 17.4 原理图绘制

OrCAD Capture CIS 17.4 原理图绘制

qq_38960013的博客 7653

LeetCode61——给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

题目:给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 思想:假设n个元素,即把后面n-k个元素依次头插即可 代码展示: /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ st...

qq_39690007的博客 3186

Atlas 300I Duo - vllm部署Qwen3-VL-8B-Instruct

本文介绍了在Ascend NPU环境下部署Qwen3-VL-8B大语言模型的步骤。主要包括:1)安装驱动、docker和vllm镜像;2)创建特权容器并挂载设备与目录;3)进入容器安装指定版本的transformers;4)设置环境变量和NPU卡配置;5)启动vllm服务;6)测试API接口。部署过程涉及多块NPU卡的使用,需注意内存碎片化问题,最终通过vllm框架提供模型推理服务。

m0_50105717的博客 1576

告别 DEFINE VIEW:CDS View Entity 迁移全景实战(报表迁移 + ADT 向导 + 避坑清单)

CDS迁移的关键要点与策略 CDS DDIC-based View已被标记为废弃,迁移到CDS View Entity成为必要。迁移面临的主要挑战包括激活成本、命名约束和依赖风险。ABAP 7.57及以上版本必须优先处理,否则将积累技术债务。 迁移方式主要有两种: 报表路线:适合渐进式迁移的On-Premise项目 ADT向导:适合云环境批量迁移 关键注意事项: 必须提前检查SQL View依赖关系 金额/数量字段需要显式引用单位/货币字段 建议按使用场景分批迁移 最佳实践是结合报表进行系统盘点,再通过AD

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 211

力扣刷题(python)50天——第二十一天:旋转链表

力扣刷题(python)50天——第二十一天:旋转链表 题目描述 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3-&...

weixin_44568780的博客 222

SAP FICO应付票据平台开发说明书(包括测试样例、程序代码仅作参考,不保证一定可以运行)

SAP FICO应付票据平台开发说明书(包括测试样例、程序代码仅作参考,不保证一定可以运行)

我好像病了的博客 383

力扣:(61)旋转链表(Python)

给你一个链表的头节点head,旋转链表,将链表每个节点向右移动k个位置。

2503_91125378的博客 225

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Python描述 LeetCode 61. 旋转链表

给你一个链表的头节点 ,旋转链表,将链表每个节点向右移动 个位置。示例 1:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SJIaR6Vv-1655343200285)(https://assets.leetcode.com/uploads/2020/11/13/rotate1.jpg)] 示例 2:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5oPBES9q-1655343200286)(https://assets.leetcode.

一起加油 630

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

LeetCode题解(python)-61. 旋转链表

LeetCode题解(python) 61. 旋转链表 题目描述 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3-&...

Marshal Zheng的博客 382

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

LeetCode:61. 旋转链表(python)

LeetCode:61. 旋转链表(python) 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4-&...

wk的博客 590

61. 旋转链表、Leetcode的Python实现

旋转链表,将链表每个节点向右移动。给你一个链表的头节点。

分享包括但不限于计算机基础知识、数据结构与算法、Golang技术栈。年与时驰,意与日去,遂成枯落,多不接世,悲守穷庐,将复何及! 797

LeetCode-Python-61. 旋转链表

给定一个链表,旋转链表,将链表每个节点向右移动k个位置,其中k是非负数。 示例1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4->NULL 向右旋转 2 步: 4->5...

Keep Coding 1225

leetcode 61. 旋转链表 python

题目描述:力扣 题目要求输入一个链表的头节点head和一个整数k,输出将链表右移k个位置的链表。 题解: 基本思路: 1.确定输入链表的长度length。 2.将第length-k个节点的next节点设为空。 3.将第length-k+1个节点作为新的链表的头节点,将链表中最后一个节点的next设为原来的head节点。 需要注意的部分: 1.如果输入链表只有一个节点或者为空,无论k为多少直接返回head. 2.当k比链表长度length大时,旋转k位的结果和旋转k%leng..

ganggang的博客 495

leetcode 61:旋转链表(python)

腾讯精选练习(50 题)Day21 leetcode 61:旋转链表(python)

nanashi_F的博客 214

leetcode-腾讯精选练习(50 题)python #61 旋转链表

leetcode-腾讯精选练习(50 题)python #61 旋转链表 题目来源:https://leetcode-cn.com/problemset/50/ 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2-&g...

楚天云 248

力扣:61. 旋转链表(Python3)

力扣:61. 旋转链表(Python3)

欢迎光临 443

【Leetcode_总结】61. 旋转链表 - python

Q: 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL, k = 2 输出: 4-&gt;5-&gt;1-&gt;2-&gt;3-&gt;NULL 解释: 向右旋转 1 步: 5-&gt;1-&gt;2-&gt;3-&gt;4-&gt;NULL 向右旋转 2 步

maka_uir的博客 318

LeetCode Python - 61. 旋转链表

否则,我们用快慢指针,让快指针先走 k 步,然后快慢指针同时走,直到快指针走到链表尾部,此时慢指针的下一个节点就是新的链表头节点。给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。否则,我们先统计链表节点数 n,然后将 k 对 n 取模,得到 k 的有效值。我们先判断链表节点数是否小于 2,如果是,直接返回 head 即可。输入:head = [1,2,3,4,5], k = 2。输入:head = [0,1,2], k = 4。输出:[4,5,1,2,3]

xuxu96 646
上一篇: Floyd判圈算法(龟兔赛跑算法)
下一篇: pandas进行分组统计
心之所向丶7
博客等级 码龄11年 17粉丝 59原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址