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里的够不够,如果不够,先读到够为止。

  1. // Forward declaration of the read4 API.
  2. int read4(char *buf);
  3. class Solution {
  4. public:
  5. /**
  6. * @param buf Destination buffer
  7. * @param n   Maximum number of characters to read
  8. * @return    The number of characters read
  9. */
  10. int read(char *buf, int n) {
  11. if(n == 0)
  12. return 0;
  13. int total = 0;
  14. while(this->buffer.size() < n && !this->endOfFile) {
  15. char* temp = new char[4];
  16. int r = read4(temp);
  17. if(r < 4)
  18. this->endOfFile = true;
  19. for(int i = 0; i < r; i++)
  20. this->buffer.push(temp[i]);
  21. }
  22. int l = min((int)this->buffer.size(), n);
  23. for(int i = 0; i < l; i++) {
  24. buf[i] = this->buffer.front();
  25. this->buffer.pop();
  26. total++;
  27. }
  28. return total;
  29. }
  30. private:
  31. queue<char> buffer;
  32. bool endOfFile = false;
  33. };

156. Binary Tree Upside Down

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
TreeNode *upsideDownBinaryTree(TreeNode *root) {
TreeNode *temp, *newRoot = NULL;
temp = buildUpsideDownBT(root, newRoot);
return newRoot;
} TreeNode *buildUpsideDownBT(TreeNode *root, TreeNode *&newRoot) {
if(!root) return root;
if(!root->left && !root->right) {
newRoot = root;
return root;
}
TreeNode *parent = buildUpsideDownBT(root->left, newRoot);
parent->left = root->right;
parent->right = root;
root->left = root->right = NULL;
return parent->right;
}
};

总结:
1. 这个递归的核心是,每次建立好一个新的子树后,要返回新子树的最右节点(ln 19),以便上层的节点可以接回到这个节点的下面。
2. 但如果只返回最右节点,则我们无法知道最后整个新树的根在哪里。所以再base case里必须给新根赋值(ln 12)
3. 每次需要reset最右节点的left/right node,否则最后一层递归,递归到例子中的1节点时,返回前1节点的left/right node仍然为原来的值,而并不为NULL。

这题有一个重要的限制就是,整个数的任何一个右孩子都不会再生枝节,基本就是一个梳子的形状。对于树类型的题目,首先可以想到一种递归的思路:把左子树继续颠倒,颠倒完后,原来的那个左孩子的左右孩子指针分别指向原来的根节点以及原来的右兄弟节点即可

  1. public TreeNode UpsideDownBinaryTree(TreeNode root) {
  2. if (root == null)
  3. return null;
  4. TreeNode parent = root, left = root.left, right = root.right;
  5. if (left != null) {
  6. TreeNode ret = UpsideDownBinaryTree(left);
  7. left.left = right;
  8. left.right = parent;
  9. return ret;
  10. }
  11. return root;
  12. }

第二个思路是直接用迭代代替递归,做起来也不麻烦,并且效率会更高,因为省去了递归所用的栈空间。

  1. public TreeNode UpsideDownBinaryTree(TreeNode root) {
  2. TreeNode node = root, parent = null, right = null;
  3. while (node != null) {
  4. TreeNode left = node.left;
  5. node.left = right;
  6. right = node.right;
  7. node.right = parent;
  8. parent = node;
  9. node = left;
  10. }
  11. return parent;
  12. }

第三个思路比较特别,把后续遍历转换成层次遍历。注意由于Java不支持对TreeNode地址传引用,所以这里弄了一个全局变量。另外,类似于对链表的处理,这里我弄了一个dummy node简化对根节点的处理。

    1. private TreeNode out = null;
    2. public TreeNode UpsideDownBinaryTree(TreeNode root) {
    3. TreeNode dummy = new TreeNode(0);
    4. dummy.left = new TreeNode(0);
    5. out = dummy;
    6. postorder(root);
    7. return dummy.right;
    8. }
    9. private void postorder(TreeNode root) {
    10. if (root == null)
    11. return;
    12. postorder(root.left);
    13. postorder(root.right);
    14. if (out.left == null) {
    15. out.left = root;
    16. out.left.left = null;
    17. out.left.right = null;
    18. } else if (out.right == null) {
    19. out.right = root;
    20. out.right.left = null;
    21. out.right.right = null;
    22. }
    23. if (out.left != null && out.right != null)
    24. out = out.right;
    25. }

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:

  1. We insert a character into S to get T.
  2. We delete a character from S to get T.
  3. We substitute a character of S to get T.

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的更多相关文章

  1. 我为什么要写LeetCode的博客?

    # 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...

  2. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  3. [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 ...

  4. 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 ...

  5. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  6. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  7. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

  8. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  9. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

随机推荐

  1. Linux 下安装 SVN服务器

    前段时间换了一个新项目组.过去发现居然SVN都没有.代码都是手动对比存档.当时就蛋疼了.这他妈也太苦逼了.话不多说,要来测试服务器地址.开工了.由于服务器不能连接外网. 1.先下载安装包.本次安装不结 ...

  2. 事件处理(Event Handlers) ng-click操作

    事件处理(Event Handlers) ng-click操作 step 10 本文主要通过介绍ng-click方法来对angularjs中的事件处理方法做个了解. 1.切换目录 git checko ...

  3. 简单的三层asp.net webForm使用Ninject实现Ioc

    简单的三层asp.net webForm使用Ninject实现Ioc 在asp.net webform下使用Ninject的简单过程. 首先建立个项目,如下图,简单三层(PS:UI层要同时引用BLL. ...

  4. boost------signals2的使用2(Boost程序库完全开发指南)读书笔记

    1.应用于观察者模式 本小节将使用signals2开发一个完整的观察者模式示例程序,用来演示信号/插槽的用法.这个程序将模拟一个日常生活场景:客人按门铃,门铃响,护士开门,婴儿哭闹. Ring.h: ...

  5. 【欧拉计划4】Largest palindrome product

    欢迎访问我的新博客:http://www.milkcu.com/blog/ 原文地址:http://www.milkcu.com/blog/archives/1371281760.html 原创:[欧 ...

  6. 怎么让猫吃辣椒 转载自 xiaotie

    典故: 某日,毛.周.刘三人聊天. 毛:怎么能让猫自愿吃辣椒? 刘:掐着脖子灌. 毛:强迫不是自愿. 周: 先饿几天,再混到猫爱吃的东西里. 毛:欺骗不是自愿.把辣椒涂到猫肛门上,它就会自己去舔了. ...

  7. jQuery的奥秘

    颜海镜 高效jQuery的奥秘 讨论jQuery和javascript性能的文章并不罕见.然而,本文我计划总结一些速度方面的技巧和我本人的一些建议,来提升你的jQuery和javascript代码.好 ...

  8. 模块化开发AraeRegistration

    .NET/ASP.NET MVC(模块化开发AraeRegistration) 阅读目录: 1.开篇介绍 2.AreaRegistration注册路由(传递路由上下文进行模块化注册) 1]开篇介绍 A ...

  9. [每日一题] OCP1z0-047 :2013-07-29 视图――别名

    本题的考点是如何创建视图,对于视图的详细知识点,可以参考我的博客: http://blog.csdn.net/guoyjoe/article/details/8614677 好,接下来我们来做测试,先 ...

  10. 初探中间件(middleware)

    初探中间件(middleware) 因为考虑到文章的长度, 所以 BaseHandler 的展开被推迟了. 在 BaseHandler 中隐藏着中间件的信息, 较常见的 SessionMiddlewa ...