首页 > 其他 > 详细

3 - Two Pointers Algorithm

时间:2019-04-20 10:06:46      阅读:124      评论:0      收藏:0      [点我收藏+]

228. Middle of Linked List

https://www.lintcode.com/problem/middle-of-linked-list/description?_from=ladder&&fromId=1

快慢指针,快指针每次走两步,慢指针每次一步。快指针到尾的时候,慢指针就是中点,时间复杂度为O(n / 2)

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: the head of linked list.
     * @return: a middle node of the linked list
     */
    public ListNode middleNode(ListNode head) {
        // write your code here
        if(head == null || head.next == null) return head;
        ListNode slow = head, fast = head.next;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}

 

3 - Two Pointers Algorithm

原文:https://www.cnblogs.com/jenna/p/10739754.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!