LeetCode 第25题
有些题代码写的还是挺优美的。哈哈
/**
* 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 reverseKGroup(ListNode head, int k) {
if(null == head || k == 1) {
return head;
}
ListNode res = fun(head, k, head);
return res;
}
public boolean checkNodeEnough(ListNode head, int k) {
int count = 0;
ListNode temp = head;
while(temp != null && count < k) {
count++;
temp = temp.next;
}
return count < k ? false : true;
}
public ListNode fun(ListNode head, int k, ListNode tail) {
ListNode temp = head;
int count = 1;
while(count < k) {
count++;
head = tail.next;
tail.next = head.next;
head.next = temp;
temp = head;
}
if(checkNodeEnough(tail.next, k)) {
tail.next = fun(tail.next, k, tail.next);
}
return temp;
}
}
最近LeetCode的内存消耗有点不准确,总是显示击败5%左右的用户,我的写法里,这道题的空间复杂度应该是O(1)
时间复杂度应该是O(n),只是遍历了两次链表
补一个遇到的面试题,k个一组翻转的简化版
class Solution {
public ListNode reverseBetween (ListNode head, int m, int n) {
if(m == n){
return head;
}
ListNode res = head;
int count = 1;
ListNode before = head;
while(count < m){
before = head;
head = head.next;
count++;
}
int changeCount = 0;
ListNode tempHead = head;
while(changeCount < n-m){
ListNode temp = head.next;
head.next = temp.next;
temp.next = tempHead;
tempHead = temp;
changeCount++;
}
if(before != head){
before.next = tempHead;
}
if(res == head){
return tempHead;
}
return res;
}
}
面试的时候不能debug,有点小细节还是蛮难想的,不debug还真不好完全解出来