上锁 - leetcode
158. Read N Characters Given Read4 II - Call multiple times
题目:
The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that readsn characters from the file.
Note:
The read function may be called multiple times.
题解:
需要用Queue保存之前多读的character。每次读时,先看Queue里的够不够,如果不够,先读到够为止。
- // Forward declaration of the read4 API.
- int read4(char *buf);
- class Solution {
- public:
- /**
- * @param buf Destination buffer
- * @param n Maximum number of characters to read
- * @return The number of characters read
- */
- int read(char *buf, int n) {
- if(n == 0)
- return 0;
- int total = 0;
- while(this->buffer.size() < n && !this->endOfFile) {
- char* temp = new char[4];
- int r = read4(temp);
- if(r < 4)
- this->endOfFile = true;
- for(int i = 0; i < r; i++)
- this->buffer.push(temp[i]);
- }
- int l = min((int)this->buffer.size(), n);
- for(int i = 0; i < l; i++) {
- buf[i] = this->buffer.front();
- this->buffer.pop();
- total++;
- }
- return total;
- }
- private:
- queue<char> buffer;
- bool endOfFile = false;
- };
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
For example:
Given a binary tree {1,2,3,4,5},
1
/ \
2 3
/ \
4 5
return the root of the binary tree [4,5,2,#,#,3,1].
4
/ \
5 2
/ \
3 1
1 |
class Solution {
|
总结:
1. 这个递归的核心是,每次建立好一个新的子树后,要返回新子树的最右节点(ln 19),以便上层的节点可以接回到这个节点的下面。
2. 但如果只返回最右节点,则我们无法知道最后整个新树的根在哪里。所以再base case里必须给新根赋值(ln 12)
3. 每次需要reset最右节点的left/right node,否则最后一层递归,递归到例子中的1节点时,返回前1节点的left/right node仍然为原来的值,而并不为NULL。
这题有一个重要的限制就是,整个数的任何一个右孩子都不会再生枝节,基本就是一个梳子的形状。对于树类型的题目,首先可以想到一种递归的思路:把左子树继续颠倒,颠倒完后,原来的那个左孩子的左右孩子指针分别指向原来的根节点以及原来的右兄弟节点即可。
- public TreeNode UpsideDownBinaryTree(TreeNode root) {
- if (root == null)
- return null;
- TreeNode parent = root, left = root.left, right = root.right;
- if (left != null) {
- TreeNode ret = UpsideDownBinaryTree(left);
- left.left = right;
- left.right = parent;
- return ret;
- }
- return root;
- }
第二个思路是直接用迭代代替递归,做起来也不麻烦,并且效率会更高,因为省去了递归所用的栈空间。
- public TreeNode UpsideDownBinaryTree(TreeNode root) {
- TreeNode node = root, parent = null, right = null;
- while (node != null) {
- TreeNode left = node.left;
- node.left = right;
- right = node.right;
- node.right = parent;
- parent = node;
- node = left;
- }
- return parent;
- }
第三个思路比较特别,把后续遍历转换成层次遍历。注意由于Java不支持对TreeNode地址传引用,所以这里弄了一个全局变量。另外,类似于对链表的处理,这里我弄了一个dummy node简化对根节点的处理。
- private TreeNode out = null;
- public TreeNode UpsideDownBinaryTree(TreeNode root) {
- TreeNode dummy = new TreeNode(0);
- dummy.left = new TreeNode(0);
- out = dummy;
- postorder(root);
- return dummy.right;
- }
- private void postorder(TreeNode root) {
- if (root == null)
- return;
- postorder(root.left);
- postorder(root.right);
- if (out.left == null) {
- out.left = root;
- out.left.left = null;
- out.left.right = null;
- } else if (out.right == null) {
- out.right = root;
- out.right.left = null;
- out.right.right = null;
- }
- if (out.left != null && out.right != null)
- out = out.right;
- }
161.One Edit Distance
Given two strings S and T, determine if they are both one edit distance apart.
we can transform S to T by using exactly one edit operation. There are three possible cases:
- We insert a character into
Sto getT. - We delete a character from
Sto getT. - We substitute a character of
Sto getT.
The code is as follows. If you find the first half of the return statement (!mismatch && (n - m == 1)) hard to understand, run the code on cases that the mismatch only occurs at the last character of the longer string, like S = "ab" and T = "abc".
class Solution {
public:
bool isOneEditDistance(string s, string t) {
int m = s.length(), n = t.length();
if (m > n) return isOneEditDistance(t, s);
if (n - m > 1) return false;
bool mismatch = false;
for (int i = 0; i < m; i++) {
if (s[i] != t[i]) {
if (m == n) s[i] = t[i];
else s.insert(i, 1, t[i]);
mismatch = true;
break;
}
}
return (!mismatch && n - m == 1) || (mismatch && s == t);
}
};
163. Missing Ranges
Given a sorted integer array where the range of elements are [lower, upper] inclusive, return its missing ranges.
For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].
class Solution {
public:
string get_range(int start, int end)
{
return start==end? to_string(start) : to_string(start)+"->"+to_string(end);
}
vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
vector<string> result;
int pre = lower-1;
for(int i =0; i <= nums.size(); i++)
{
int cur = (i==nums.size()? upper+1:nums[i]);
if(cur-pre>=2)
result.push_back(get_range(pre+1,cur-1));
pre = cur;
}
return result;
}
};
170. [LeetCode] Two Sum III - Data structure design 两数之和之三 - 数据结构设计
Design and implement a TwoSum class. It should support the following operations:add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
class TwoSum{
public:
void add(int number){
hash[number]++;
}
bool find(int number){
for(int i : hash){
int target = number - i.first;
if(hash.find(target) != hash.end()){
return true;
}
}
return false;
}
private:
unordered_map<int, int>hash;
};
LeetCode 186. Reverse Words in a String II(反转单词)
上锁 - leetcode的更多相关文章
- 我为什么要写LeetCode的博客?
# 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...
- LeetCode All in One 题目讲解汇总(持续更新中...)
终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...
- [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串
Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...
- Leetcode 笔记 113 - Path Sum II
题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...
- Leetcode 笔记 112 - Path Sum
题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...
- Leetcode 笔记 110 - Balanced Binary Tree
题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...
- Leetcode 笔记 100 - Same Tree
题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...
- Leetcode 笔记 99 - Recover Binary Search Tree
题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...
- Leetcode 笔记 98 - Validate Binary Search Tree
题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...
随机推荐
- [推荐分享]大量Javascript/JQuery学习教程电子书合集,送给有需要的人
不收藏是你的错^_^. 经证实,均可免费下载. 资源名称 资源大小 15天学会jQuery(完整版).pdf 274.79 KB 21天学通JavaScript(第2版)-顾宁燕扫描版.pdf ...
- 从Java到C (大纲)
Binder机制,从Java到C (大纲) 转载请标注:张小燕:http://www.cnblogs.com/zhangxinyan/p/3487381.html 前段时间一直在看有关Binder ...
- W3C的CORS Specification
W3C的CORS Specification 随着Web开放的程度越来越高,通过浏览器跨域获取资源的需求已经变得非常普遍.在我看来,如果Web API不能针对浏览器提供跨域资源共享的能力,它甚至就不应 ...
- nhibernate+autofac+mvc的demo
想自己做一个小的demo.目的是能够提供一个系统架构,在这个基础上,可以快速开发一些小型的系统.
- JavaScript学习--(智能社视频)
JavaScript学习,这是智能社官网上的JS视频,讲解的挺不错的,就是没有视频的demo,在视频中附上自己编写的一些demo... 下载地址:http://pan.baidu.com/s/1cPz ...
- GTK+编程概述
目标 什么是GTK? 怎样做一个GTK应用程序 事件(Events).信号(Signals).回调函数(Callbacks) 组件(widgets) 引言 GIMP工具包(GTK+)最初被设计为一个光 ...
- [转]Adventures in Xen exploitation
Source:https://www.nccgroup.com/en/blog/2015/02/adventures-in-xen-exploitation/ tl;dr This post is ...
- Java并发性和多线程介绍
java并发性和多线程介绍: 单个程序内运行多个线程,多任务并发运行 多线程优点: 高效运行,多组件并行.读->操作->写: 程序设计的简单性,遇到多问题,多开线程就好: 快速响应,异步式 ...
- jquery.post用法补充(type设置问题)
jquery.post用法 http://blog.csdn.net/itmyhome1990/article/details/12578275 当使用ajax获取data数据的时候,直接data.f ...
- 微信公众平台自定义菜单创建代码实现—java版
搞了两天的自定义菜单,终于搞定了,现在分享下心得,以便后来者少走弯路...... 好了,先看先微信官方的API 官方写的很详细,但是我看完后很茫然,不知道你们什么感觉. 我知道是post一个带参数的 ...