LeetCode
来源:互联网 发布:网页设计程序员工资 编辑:程序博客网 时间:2024/05/29 18:30
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
.
一个链表的,重新衔接。
最开始一直TLE,我还十分纳闷,不可能发生死循环啊。然后发现链表头尾衔接后不是代码死循环,是输出死循环了orzzzzzzz
思路就是将链表形成环,然后在合适的地方断开(然额最开始我天真地以为我只是增加了长度。。)时间复杂度O(n),空间复杂度O(1)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* rotateRight(ListNode* head, int k) { if (!head) return head; int cnt = 1; ListNode* cur = head; ListNode* ans = head; while (cur->next) { cnt++; cur = cur->next; } cur->next = head; if (k %= cnt) { for (int i = 0; i < cnt - k; ++i) cur = cur->next; } ans = cur->next; cur->next = NULL; //断开!!!断开!!! return ans; }};
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- windows服务安装,动态配置服务信息
- django中的认证(含自定义认证)与登录
- HTML5 Plus 拍照或者相册选择图片上传
- Selectable.interactable -->设置UI可否被点击
- [RK3288][Android6.0] 调试笔记 --- Audio分离DTMF tone引起的异常
- LeetCode
- 使用ajax方法实现form表单的提交(附源码)
- VMware Workstation 12下安装Mac OS X系统。
- Android中 Context的用法
- 模拟实现一个Stack 要求实现Push(出栈)、Pop(入栈)、Min(返回最小值的操作)的时间复杂度为O(1)
- 剑指offer29:数组中出现次数超过一半的数字
- 上传ipa错误以及解决方法记录:
- css选择器优先级计算以及伪元素与伪类区别
- Spring思维导图,让Spring不再难懂(mvc篇)