Leetcode 61. Rotate List

GoodJobJasper發表於2020-12-26

在這裡插入圖片描述
方法1: 每次向右移動一次,但是這個方法tle。時間複雜度n平方。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

// recursion & iterate
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next ==null) return head;
        ListNode temp = head;
        while(k > 0){
            temp = rotateOneRight(temp);
            k--;
        }
        return temp;
    }
    
    private ListNode rotateOneRight(ListNode head){
        ListNode curr = head;
        ListNode prev = new ListNode(0);
        while(curr.next != null){
            prev = curr;
            curr = curr.next;
        }
        prev.next = null;
        curr.next = head;
        return curr;
    }
}

方法2: lc官方解答,有點類似數學,需要推算出移動過後新head和新tail的位置。時間複雜度n,空間複雜度1.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k){ 
        if(head ==null || head.next == null) return head;
        ListNode curr = head;
        int count = 1;
        while(curr.next !=  null){
            curr = curr.next;
            count++;
        }
        curr.next = head;
        int newTailPosition = count - k % count - 1;
        int newHeadPosition = count - k;
    
        ListNode new_tail = head;    
        for(int i = 0; i < newTailPosition; ++i){
            new_tail = new_tail.next;
        }
        ListNode new_head = new_tail.next;
        new_tail.next = null;
    
        return new_head;
    }
}

總結:

  • 還是比較經典的node移動問題,非常鍛鍊思維,不錯的題目。

相關文章