leetcode 61.Rotate List
来源:互联网 发布:网易企业邮箱域名设置 编辑:程序博客网 时间:2024/05/23 18:36
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
题目意思就是往右将list移动k个位置,这里需要注意的是k可能大于list的长度,因此首先求取list的长度是需要的。
本题最主要设置2个指针,位置相差k。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head == null){ return head; } ListNode pre = head; int length = 0; while(pre != null){ pre = pre.next; length++; } k = k % length; pre = head; ListNode tal = head; for(int j = 0; j < k; j++){ tal = tal.next; } while(tal.next != null){ tal = tal.next; pre = pre.next; } tal.next = head; head = pre.next; pre.next = null; return head; }}
这里出现冗余的地方是两个指针的位置,可以看到,最后tal指针停下来的位置是list的最后一个节点,与求长度时pre指针的停下的位置相同,因此tal指针不需要额外再使用循环了,只需要找到pre的位置即可。
<pre name="code" class="java">/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head == null){ return head; } ListNode pre = head; ListNode tal = head; int length = 1; while(tal.next != null){ tal = tal.next; length++; } k = k % length; for(int i = 0; i < length - k - 1; i++){ pre = pre.next; } tal.next = head; head = pre.next; pre.next = null; return head; }}
虽然减少了一个for循环,但从测试结果来看,时间上差不多,都是1ms,但这样思路也更清晰了些。
0 0
- [LeetCode]61.Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- leetcode 61. Rotate List
- [LeetCode]61. Rotate List
- LeetCode 61. Rotate List
- LeetCode *** 61. Rotate List
- LeetCode 61. Rotate List
- [Leetcode]61. Rotate List
- LeetCode - 61. Rotate List
- android 音频采集1
- 常用的刷新技术(二)——Ultra-Pull-To-Refresh
- halcon+大恒水星相机图像采集
- uva-1484(hdu-3660) Alice and Bob's Trip 听说是树形dp
- sort,qsort,bsearchs函数的用法
- leetcode 61.Rotate List
- win上面配置本地MySQL主从
- webbrowser 里的js调用C#窗体的函数
- POJ 2135 Farm Tour (最小费用最大流模版)
- 史上最详细的Log4j配置
- Linux下的jdk安装
- centos7防火墙firewalld守护进程
- 详解数据库范式
- git到一个非空项目上