Leetcode 61. Rotate List
方法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移動問題,非常鍛鍊思維,不錯的題目。
相關文章
- [LeetCode] 61. Rotate ListLeetCode
- Leetcode Rotate ListLeetCode
- Leetcode-Rotate ListLeetCode
- Rotate List leetcode javaLeetCodeJava
- 【LeetCode】 Rotate List 迴圈連結串列LeetCode
- Leetcode Rotate ImageLeetCode
- Rotate Array@LeetCodeLeetCode
- [LeetCode] Rotate StringLeetCode
- LeetCode-Rotate FunctionLeetCodeFunction
- LeetCode-Rotate ArrayLeetCode
- Leetcode-Rotate ImageLeetCode
- Rotate Image leetcode javaLeetCodeJava
- 【Leetcode】61.旋轉連結串列LeetCode
- leetcode刷題--Rotate ArrayLeetCode
- Leetcode Partition ListLeetCode
- LeetCode-Reorder ListLeetCode
- Leetcode-Partition ListLeetCode
- Leetcode-Sort ListLeetCode
- Partition List leetcode javaLeetCodeJava
- Reorder List leetcode javaLeetCodeJava
- Sort List leetcode javaLeetCodeJava
- 【LeetCode從零單排】No189 .Rotate ArrayLeetCode
- canvas rotate()Canvas
- 【Leetcode】86. Partition ListLeetCode
- Leetcode Insertion Sort ListLeetCode
- leetcode Linked List CycleLeetCode
- Leetcode Copy List with Random PointerLeetCoderandom
- 61. 路由 路由模型繫結路由模型
- 61. 旋轉連結串列
- [LeetCode] 148. Sort ListLeetCode
- LeetCode | 148. Sort ListLeetCode
- 【Leetcode】143. Reorder ListLeetCode
- LeetCode-Flatten Nested List IteratorLeetCode
- LeetCode148:Sort ListLeetCode
- LeetCode143:Reorder ListLeetCode
- Leetcode Reverse Linked List IILeetCode
- Leetcode Remove Duplicates from Sorted ListLeetCodeREM
- Leetcode Linked List Cycle IILeetCode