快慢指针
- 时间复杂度O(n),空间复杂度O(1)
- 执行用时:76 ms, 在所有 JavaScript 提交中击败了52.36%的用户
- 内存消耗:39 MB, 在所有 JavaScript 提交中击败了91.02%的用户
/**
* 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 fast = head;
let slow = head;
while (fast && k > 0) {
k--;
fast = fast.next;
}
while (fast) {
fast = fast.next;
slow = slow.next;
}
return slow;
};
网友评论