随笔分类 -  LeetCode

摘要:Given a linked list, determine if it has a cycle in it.Follow up:Can you solve it without using extra space?关于这个问题可以参考http://leonax.net/p/1960/find-circle-in-linked-list/。由于每一个父亲只有可能有一个孩子,故这里的环实际上是指list中某一个节点的孩子同时也是它自己或者他的祖先。 这个问题需要注意几种情况:1. 空链表不成环2. 一个节点自环3. 一条链表完整成环不能开额外的空间,即空间复杂度是o(1)。该问题是经典面试问题, 阅读全文
posted @ 2013-11-08 17:32 xchangcheng 阅读(2533) 评论(0) 推荐(0)
摘要:Given an array of integers, every element appearstwiceexcept for one. Find that single one.Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?感谢cnblog博主feiling,这篇博客一方面参考了feiling的博客,也加入了自己的一些看法。[解题思路]要求线性时间复杂度,同时空间复杂度为O(1),即只允许开常数个空间。最直接的思路是 阅读全文
posted @ 2013-11-08 07:43 xchangcheng 阅读(10966) 评论(18) 推荐(3)
摘要:Given two binary trees, write a function to check if they are equal or not.Two binary trees are considered equal if they are structurally identical and the nodes have the same value./** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * ... 阅读全文
posted @ 2013-11-07 23:32 xchangcheng 阅读(205) 评论(0) 推荐(0)
摘要:Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.这道题非常直接,只需要递归深搜就可以。需要注意的是递归的终止条件:root为空,深度为0;root没有孩子,深度为1。如果存在孩子,则递归深搜下去。/** * Definition for binary tree * struct TreeNode { * int val; ... 阅读全文
posted @ 2013-11-07 21:15 xchangcheng 阅读(181) 评论(0) 推荐(0)