Giter VIP home page Giter VIP logo

Comments (4)

callqh avatar callqh commented on June 7, 2024

思路

[其实有两种解法。一种相对暴力的解法就是对链表进行两次遍历,一次找出链表的总长度,另一次就是找到n-k个节点就是倒数第k个节点。
而我们这里采用一种一遍遍历就可以解决的方法。

  1. 定义两个指针都指向链表的起始节点
  2. 先让一个指针p2,提前走k
  3. 这时另一个指针p1p2,之间相差的距离就是k,然后让两个指针同时移动
  4. p2===null时,说明链表结束,那么这时p1指向的就是倒数第k个节点

from algorithm.

callqh avatar callqh commented on June 7, 2024

相对暴力的解法:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var getKthFromEnd = function(head, k) {
    let p = head,p1=head;
    let count = 0;
    while(p!==null){
        count++;
        p = p.next;
    }
    for(let i = 0; i < count-k; i++){
        p1=p1.next;
    }
    return p1;
};

from algorithm.

callqh avatar callqh commented on June 7, 2024

其实这样看来上述两种算法的时间复杂度都是O(n),但是第一种更有技巧性,比较能装逼

from algorithm.

callqh avatar callqh commented on June 7, 2024

如果更细了说第一种算法其实指针移动的次数更少

from algorithm.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.