摘要:而后吾當依除取余之法,化大為小,則指針不致于越界也。后欲尋右起第結(jié)點,令快指針先行數(shù)日,及至兩指針相距為,便吟鞭東指,與慢指針策馬共進。快慢指針亦止于其所焉。舞動長劍,中宮直入,直取首級,而一掌劈空,已鴻飛冥冥。自此,一代天驕,霸業(yè)已成。
Problem
Given a list, rotate the list to the right by k places, where k is non-negative.
ExampleGiven 1->2->3->4->5 and k = 2, return 4->5->1->2->3.
Note這是一道有故事的題目。
k有多大?其翼若垂天之云,則或長于鏈表。鏈表幾長?北海也,天池也,其廣數(shù)千里,則k亦可容于鏈表也。
故吾必先窮盡鏈表之長度,如若head為null,抑或其長可為k所整除,則此題不必再做,返回head可也。
而后吾當依除len取余之法,化大k為小k,則指針不致于越界也。后欲尋右起第k結(jié)點,令快指針先行數(shù)日,及至兩指針相距為k,便吟鞭東指,與慢指針策馬共進。則快指針行至null時,慢指針可至右起第k處矣。
方是時也,孤燈長夜,指飛鍵落。如風吹敗葉,雨打窗欞。快慢指針亦止于其所焉。此時看官不妨溫酒一盞,看那鏈表翻轉(zhuǎn),指針易位。那新頭目喚作curhead,正是slow所指之人。fast舞動長劍,中宮直入,直取head首級,而slow一掌劈空,null已鴻飛冥冥。
自此,curhead一代天驕,霸業(yè)已成。
public class Solution { public ListNode rotateRight(ListNode head, int k) { ListNode fast = head, slow = head; int len = 0; while (fast != null) { fast = fast.next; len++; } if (head == null || k % len == 0) return head; fast = head; k = k % len; while (k-- > 0) fast = fast.next; while (fast.next != null) { fast = fast.next; slow = slow.next; } ListNode curhead = slow.next; slow.next = null; fast.next = head; return curhead; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/65689.html
Problem Given an array, rotate the array to the right by k steps, where k is non-negative. Example Example 1: Input: [1,2,3,4,5,6,7] and k = 3Output: [5,6,7,1,2,3,4]Explanation:rotate 1 steps to the r...
摘要:兩種方法,轉(zhuǎn)置鏡像法和公式法。首先看轉(zhuǎn)置鏡像法原矩陣為轉(zhuǎn)置后水平鏡像翻轉(zhuǎn)后所以,基本的思路是兩次遍歷,第一次轉(zhuǎn)置,第二次水平鏡像翻轉(zhuǎn)變換列坐標。公式法是應用了一個翻轉(zhuǎn)的公式如此翻轉(zhuǎn)四次即可。二者均可,并無分別。 Problem You are given an n x n 2D matrix representing an image.Rotate the image by 90 de...
Problem Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. Example Given intervals = [[0,30],[...
摘要:依然是一道找倒數(shù)第個結(jié)點的鏈表題,用雙指針做。先走,然后和一起走,直到為,的位置就是倒數(shù)第個位置。 Problem Find the nth to last element of a singly linked list. The minimum number of nodes in list is n. Example Given a List 3->2->1->5->null ...
摘要:大體意思就是,先復制到,順便將所有的放在再復制所有的到,順便將所有的放在最后令,令,將和分離,返回的頭結(jié)點 Problem A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. ...
閱讀 2088·2021-11-24 09:39
閱讀 1551·2021-10-11 10:59
閱讀 2499·2021-09-24 10:28
閱讀 3376·2021-09-08 09:45
閱讀 1268·2021-09-07 10:06
閱讀 1667·2019-08-30 15:53
閱讀 2061·2019-08-30 15:53
閱讀 1420·2019-08-30 15:53