成人无码视频,亚洲精品久久久久av无码,午夜精品久久久久久毛片,亚洲 中文字幕 日韩 无码

資訊專欄INFORMATION COLUMN

[LintCode/LeetCode] Nth to Last Node in List

Salamander / 2169人閱讀

摘要:依然是一道找倒數(shù)第個(gè)結(jié)點(diǎn)的鏈表題,用雙指針做。先走,然后和一起走,直到為,的位置就是倒數(shù)第個(gè)位置。

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 and n = 2, return node whose value is 1.

Note

依然是一道找倒數(shù)第n個(gè)結(jié)點(diǎn)的鏈表題,用雙指針做。fast先走n,然后fast和slow一起走,直到fast為null,slow的位置就是倒數(shù)第n個(gè)位置。

Solution
public class Solution {
    ListNode nthToLast(ListNode head, int n) {
        ListNode fast = head, slow = head;
        int i = n;
        while (i-- > 0) fast = fast.next;
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.com/yun/65704.html

相關(guān)文章

  • [LintCode/LeetCode] LRU Cache

    摘要:方法繼承了的很多方法,本身的方法有對(duì)運(yùn)行速度影響不大,隨意設(shè)定是默認(rèn)值,為浮點(diǎn)數(shù)為,與意思相同最近過(guò)的 Problem Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. ge...

    walterrwu 評(píng)論0 收藏0
  • [LintCode/LeetCode] Super Ugly Number

    摘要:建兩個(gè)新數(shù)組,一個(gè)存數(shù),一個(gè)存。數(shù)組中所有元素初值都是。實(shí)現(xiàn)的過(guò)程是,一個(gè)循環(huán)里包含兩個(gè)子循環(huán)。兩個(gè)子循環(huán)的作用分別是,遍歷數(shù)組與相乘找到最小乘積存入再遍歷一次數(shù)組與的乘積,結(jié)果與相同的,就將加,即跳過(guò)這個(gè)結(jié)果相同結(jié)果只存一次。 Problem Write a program to find the nth super ugly number. Super ugly numbers a...

    wuyumin 評(píng)論0 收藏0
  • [LintCode/LeetCode] Copy List with Random Pointer

    摘要:大體意思就是,先復(fù)制到,順便將所有的放在再?gòu)?fù)制所有的到,順便將所有的放在最后令,令,將和分離,返回的頭結(jié)點(diǎn) 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. ...

    Jacendfeng 評(píng)論0 收藏0
  • [LintCode/LeetCode] Jump Game I & II

    摘要:建立動(dòng)規(guī)數(shù)組,表示從起點(diǎn)處到達(dá)該點(diǎn)的可能性。循環(huán)結(jié)束后,數(shù)組對(duì)所有點(diǎn)作為終點(diǎn)的可能性都進(jìn)行了賦值。和的不同在于找到最少的步數(shù)。此時(shí)的一定是滿足條件的最小的,所以一定是最優(yōu)解。 Jump Game Problem Given an array of non-negative integers, you are initially positioned at the first index...

    rose 評(píng)論0 收藏0
  • [LintCode/LeetCode] Clone Graph [BFS/DFS]

    摘要:開(kāi)始看這道題目的時(shí)候,沒(méi)有看懂和的作用。然后對(duì)這個(gè)放入的結(jié)點(diǎn)開(kāi)始操作遍歷的所有,當(dāng)前遍歷到的的叫做。當(dāng)完成,則中沒(méi)有新的結(jié)點(diǎn)了,退出循環(huán)。返回在中更新過(guò)的,結(jié)束。 Problem Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. We use #...

    fredshare 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

閱讀需要支付1元查看
<