Easy-题目54:234. Palindrome Linked List
2016-05-30 20:52
344 查看
题目原文:
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
题目大意:
给一个单链表,判断它是不是回文的。
你能实现O(n)时间复杂度和O(1)空间复杂度吗?
题目分析:
如果用O(1)空间复杂度的话,可以求出链表的中点,然后翻转前半个链表再比较两个“半链表”是否相同。但是,我觉得代码太麻烦,就改用O(n)的空间复杂度了,这样的算法很简单:把链表转换成线性表,因为是随机存储的很容易判断是否是回文。
源码:(language:cpp)
成绩:
28ms,beats 9.66%,众数28ms,58.57%
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
题目大意:
给一个单链表,判断它是不是回文的。
你能实现O(n)时间复杂度和O(1)空间复杂度吗?
题目分析:
如果用O(1)空间复杂度的话,可以求出链表的中点,然后翻转前半个链表再比较两个“半链表”是否相同。但是,我觉得代码太麻烦,就改用O(n)的空间复杂度了,这样的算法很简单:把链表转换成线性表,因为是随机存储的很容易判断是否是回文。
源码:(language:cpp)
class Solution { public: bool isPalindrome(ListNode* head) { int length=0; for(ListNode* p=head;p;p=p->next,length++);//length is the length of linklist int* array=new int[length]; int i=0; for(ListNode* p=head;p;p=p->next) array[i++]=p->val; return isPalindromeArray(array,length); } bool isPalindromeArray(int* array,int length) { if(length==0||length==1) return true; else if(*array!=*(array+length-1)) return false; else return isPalindromeArray(array+1,length-2); } };
成绩:
28ms,beats 9.66%,众数28ms,58.57%
相关文章推荐
- 平面坐标系中,求点在线上的投影坐标(如图)
- SDNU1332 矩阵交换
- PL/SQL数据库开发那点事
- linux下的inode记录
- 一些错误和解决办法--01
- Easy-题目53:257. Binary Tree Paths
- A strange lift
- Easy-题目52:14. Longest Common Prefix
- 一些错误和解决办法--01
- OpenglES2.0 for Android:来画个三角形吧
- JQiery选择器中的表单元素
- Easy-题目51:203. Remove Linked List Elements
- hdu 5664 Lady CA and the graph (树分治,树状数组)
- 第十三周项目1:阅读、修改和运行关于交通工具类的程序(3)
- poj 3378 pascal
- JAVA学习笔记整理三(抽象类、接口、匿名类)
- java的动态代理机制详解 动态代理类
- 【记账小助手】项目文档(包含需要用到的知识点)
- 安卓深度探索(卷一)第八章
- Oracle 注入技巧收集