面试笔试整理6:常见面试编程题
来源:互联网 发布:电脑网络格斗游戏 编辑:程序博客网 时间:2024/05/18 00:06
1、二叉树公共父节点
leecode236
递归解法:
class Solution {public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root==NULL || root==p||root==q) return root; TreeNode *left = lowestCommonAncestor(root->left, p, q); TreeNode *right = lowestCommonAncestor(root->right, p, q); if(left && right) return root; return left?left:right; }};
非递归解法,最简单就是记录节点的父节点和其中一条路径:
class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ stack = [root] pair = {root:None} while p not in pair or q not in pair: node = stack.pop() if node.left: stack.append(node.left) pair[node.left] = node if node.right: stack.append(node.right) pair[node.right] = node #找到到达p的路径 path = set() while p : path.add(p) p = pair[p] while q not in path: q = pair[q] return q
2、树的中序遍历
//非递归中序遍历void inorderTraversal(TreeNode *root, vector<int> &path){ stack<TreeNode *> s; TreeNode *p = root; while(p != NULL || !s.empty()) { while(p != NULL) { s.push(p); p = p->left; } if(!s.empty()) { p = s.top(); path.push_back(p->val); s.pop(); p = p->right; } }}
递归版:
void inorder(TreeNode *root, vector<int> &path){ if(root != NULL) { inorder(root->left, path); path.push_back(root->val); inorder(root->right, path); }}
3、求两个已排序数组的交集
对于两个排序数组很简单,分别找两个指针指向数组头部,如果一个比另一个小就移动小的;如果相等就保存,同时两个指针都移动
public LinkedList<Integer> intersection(int[] A, int[] B) { if (A == null || B == null || A.length == 0 || B.length == 0) return null; LinkedList<Integer> list = new LinkedList<Integer>(); int pointerA = 0; int pointerB = 0; while (pointerA < A.length && pointerB < B.length) { if (A[pointerA] < B[pointerB]) pointerA++; else if (A[pointerA] > B[pointerB]) pointerB++; else { list.add(A[pointerA]); pointerA++; pointerB++; } } return list; }
对于多个数组的情况同样可以用上面的方法或者:首先找到最短的数组,接着对这个数组中的值用二分查找在其他数组中寻找。
阅读全文
0 0
- 面试笔试整理6:常见面试编程题
- 面试常见笔试题
- 常见面试笔试编程题目
- 面试心经-笔试编程整理
- 2.前端常见面试编程题整理
- Linux 笔试面试常见题目(整理)
- 笔试面试----常见算法题
- mybatis常见面试/笔试题
- mybatis常见面试/笔试题
- 常见面试编程题
- 笔试面试常见函数编程实现
- 面试笔试整理:1、笔试常见输入输出(待补充)
- 【笔试面试】经典笔试题整理
- 面试常见基础题整理
- 常见面试算法题整理
- 常见笔试/面试题目
- 笔试面试常见问答题
- 笔试面试常见智力题
- 笔、面试经验
- Java list泛型与JSON的相互转换(含jar包下载链接)
- 2017-09-17 LeetCode_027 Remove Element
- netstat命令使用
- ZooKeeperEclipse-插件
- 面试笔试整理6:常见面试编程题
- BZOJ 1095: [ZJOI2007]Hide 捉迷藏 动态树分治
- Hbase 布隆过滤器BloomFilter介绍
- [嵌入式Linux驱动]关于RFID模块的Linux控制应用程序
- 使用bootstrap框架出现glyphicons-halflings-regular.woff2 Failed一类
- Xshell 5+lrzsz实现Windows客户端向CentOS服务器上传文件
- angular组件通信
- 不得不珍藏的Chrome插件推荐
- HDU 5536 Chip Factory——Trie + 异或运算