[] 61.回転リストLeetCode回転リスト(中)(JAVA)
トピック住所:https://leetcode.com/problems/rotate-list/
件名の説明:
リンクリストを考えると、kは非負であるk桁だけ右にリストを回転させます。
例1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
例2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
効果の対象に
リスト、回転のリスト、右側にノードリストの各k個の位置によって与えられ、前記kは非負です。
問題解決のアプローチ
次いで、及び真のニーズの移動位置算出:1、算出された鎖長(K> LENのため):LEN%のK
2を、ノード、preNodeを移動させる必要性を識別する
。3、断線preNode次、全てリンクへのノード
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) return head;
ListNode temp = head;
int count = 1;
while (temp != null) {
if (temp.next == null) break;
temp = temp.next;
count++;
}
ListNode tail = temp;
k = k % count;
temp = head;
for (int i = 1; i < count - k; i++) {
temp = temp.next;
}
tail.next = head;
ListNode res = temp.next;
temp.next = null;
return res;
}
}
実行する場合:1ミリ秒、のJavaに提出するすべてのユーザーの87.45パーセントを打つ
メモリ消費量:37.9メガバイトは、Javaで提出するすべてのユーザーの14.53パーセントを破りました