LeetBook作业记录:旋转链表

作业感受

题目地址: https://leetcode-cn.com/leetbook/read/linked-list/f00a2/

其实这一看这个作业很简单,但是做的过程中发现一个很tricky的问题就是k的处理,一开始我的思路局限在k小于链表size的世界里,提交后发现错误了。后来我修改了代码,虽然正确了,但是用时很长啊。

本来想写一个递归的,但是思路还是没有理清,就用了双指针。用时长大概是因为循环了两次的原因。

作业代码

/**
 * 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)  return null;
        if(head.next == null) return head;  
        if(k == 0) return head;

        ListNode dummyHead = new ListNode(); 

        ListNode slow = head, fast = head;
               
        while(k > 0){
            fast = fast.next;
            k--;
            if(fast == null && k > 0) fast = head;
            if(fast == null && k == 0) return head;
            
        }
        
        while(slow.next != null && fast.next != null){
            slow = slow.next;
            fast = fast.next;
        }

        dummyHead.next = slow.next;
        fast.next = head;
        slow.next = null;

        return dummyHead.next;

    }
}

作业表现


1359ms…真的是心碎啊!我猜测应该是有测试用例给了一个超大的k, 于是我决定优化第一个循环。

优化后的代码

/**
 * 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)  return null;
        if(head.next == null) return head;  
        

        ListNode dummyHead = new ListNode(); 

        ListNode slow = head, fast = head;
        int size = 0;

        while(fast != null){
            fast = fast.next;
            size++;
        }

        fast = head;
        k = k % size;     

        if(k == 0) return head;
          
        while(k > 0){
            fast = fast.next;
            k--;
 
        }
        
        while(slow.next != null && fast.next != null){
            slow = slow.next;
            fast = fast.next;
        }

        dummyHead.next = slow.next;
        fast.next = head;
        slow.next = null;

        return dummyHead.next;

    }
}

果然被我猜中了,k的上限是一个很大的数,node的个数上线只是500, 看来循环条件的选择很重要啊,不然真的是伤不起啊。优化以后用时降到1ms。

优化后代码的表现

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不争之德

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值