[关闭]
@Yano 2019-09-20T10:55:39.000000Z 字数 9567 阅读 5483

LeetCode之Design题目汇总

LeetCode

公众号

coding 笔记、点滴记录,以后的文章也会同步到公众号(Coding Insight)中,希望大家关注^_^

https://github.com/LjyYano/Thinking_in_Java_MindMapping


LeetCode 题目汇总

LeetCode之Array题目汇总
LeetCode之Hash Table题目汇总
LeetCode之Linked List题目汇总
LeetCode之Math题目汇总
LeetCode之String题目汇总
LeetCode之Binary Search题目汇总
LeetCode之Divide and Conquer题目汇总
LeetCode之Dynamic Programming题目汇总
LeetCode之Backtracing题目汇总
LeetCode之Stack题目汇总
LeetCode之Sort题目汇总
LeetCode之Bit Manipulation题目汇总
LeetCode之Tree题目汇总
LeetCode之Depth-first Search题目汇总
LeetCode之Breadth-first Search题目汇总
LeetCode之Graph题目汇总
LeetCode之Trie题目汇总
LeetCode之Design题目汇总


文章目录:


Implement Queue using Stacks

Implement the following operations of a queue using stacks.

Notes:


非常经典的题目,定义两个栈模拟队列。

  1. push向stack1
  2. pop从stack2,如果stack2为空,先将stack1的元素放入stack2
  1. class MyQueue {
  2. Stack<Integer> stack1 = new Stack<Integer>();
  3. Stack<Integer> stack2 = new Stack<Integer>();
  4. // Push element x to the back of queue.
  5. public void push(int x) {
  6. stack1.push(x);
  7. }
  8. // Removes the element from in front of queue.
  9. public void pop() {
  10. if (stack2.isEmpty()) {
  11. if (stack1.isEmpty()) {
  12. throw new IllegalStateException();
  13. }
  14. while (!stack1.isEmpty()) {
  15. stack2.push(stack1.pop());
  16. }
  17. }
  18. stack2.pop();
  19. }
  20. // Get the front element.
  21. public int peek() {
  22. if (stack2.isEmpty()) {
  23. if (stack1.isEmpty()) {
  24. throw new IllegalStateException();
  25. }
  26. while (!stack1.isEmpty()) {
  27. stack2.push(stack1.pop());
  28. }
  29. }
  30. return stack2.peek();
  31. }
  32. // Return whether the queue is empty.
  33. public boolean empty() {
  34. if (stack1.isEmpty() && stack2.isEmpty()) {
  35. return true;
  36. }
  37. return false;
  38. }
  39. }

Implement Stack using Queues

Implement the following operations of a stack using queues.

Notes:

Update (2015-06-11): 
The class name of the Java function had been updated to MyStack instead of Stack.

Credits: 
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.


非常经典的题目,定义两个队列模拟栈的操作。总保持一个队列为空:

  1. push就插入到非空的队列中
  2. pop就把非空队列元素,依次放到另一个空队列中,只是最后一个元素弹出
  1. class MyStack {
  2. Queue<Integer> q1 = new LinkedList<Integer>();
  3. Queue<Integer> q2 = new LinkedList<Integer>();
  4. // Push element x onto stack.
  5. public void push(int x) {
  6. if (q1.isEmpty() && q2.isEmpty()) {
  7. q1.add(x);
  8. } else if (!q1.isEmpty()) {
  9. q1.add(x);
  10. } else {
  11. q2.add(x);
  12. }
  13. }
  14. // Removes the element on top of the stack.
  15. public void pop() {
  16. if (empty()) {
  17. throw new IllegalStateException();
  18. }
  19. // q1、q2必有一个为空
  20. if (q2.isEmpty()) {
  21. while (!q1.isEmpty()) {
  22. int x = q1.remove();
  23. if (!q1.isEmpty()) {
  24. q2.add(x);
  25. }
  26. }
  27. } else if (q1.isEmpty()) {
  28. while (!q2.isEmpty()) {
  29. int x = q2.remove();
  30. if (!q2.isEmpty()) {
  31. q1.add(x);
  32. }
  33. }
  34. }
  35. }
  36. // Get the top element.
  37. public int top() {
  38. if (empty()) {
  39. throw new IllegalStateException();
  40. }
  41. int x = 0;
  42. // q1、q2必有一个为空
  43. if (q2.isEmpty()) {
  44. while (!q1.isEmpty()) {
  45. x = q1.remove();
  46. q2.add(x);
  47. }
  48. } else if (q1.isEmpty()) {
  49. while (!q2.isEmpty()) {
  50. x = q2.remove();
  51. q1.add(x);
  52. }
  53. }
  54. return x;
  55. }
  56. // Return whether the stack is empty.
  57. public boolean empty() {
  58. if (q1.isEmpty() && q2.isEmpty()) {
  59. return true;
  60. }
  61. return false;
  62. }
  63. }

Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.


  1. class TrieNode {
  2. boolean isLeaf;
  3. char c;
  4. HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();
  5. // Initialize your data structure here.
  6. public TrieNode() {
  7. }
  8. public TrieNode(char c) {
  9. this.c = c;
  10. }
  11. }
  12. public class Trie {
  13. private TrieNode root;
  14. public Trie() {
  15. root = new TrieNode();
  16. }
  17. // Inserts a word into the trie.
  18. public void insert(String word) {
  19. HashMap<Character, TrieNode> children = root.children;
  20. for (int i = 0; i < word.length(); i++) {
  21. char c = word.charAt(i);
  22. TrieNode t;
  23. if (children.containsKey(c)) {
  24. t = children.get(c);
  25. } else {
  26. t = new TrieNode(c);
  27. children.put(c, t);
  28. }
  29. children = t.children;
  30. if (i == word.length() - 1) {
  31. t.isLeaf = true;
  32. }
  33. }
  34. }
  35. // Returns if the word is in the trie.
  36. public boolean search(String word) {
  37. HashMap<Character, TrieNode> children = root.children;
  38. for (int i = 0; i < word.length(); i++) {
  39. char c = word.charAt(i);
  40. if (!children.containsKey(c)) {
  41. return false;
  42. }
  43. if (i == word.length() - 1) {
  44. if (children.get(c).isLeaf == true) {
  45. return true;
  46. }
  47. return false;
  48. }
  49. children = children.get(c).children;
  50. }
  51. // useless
  52. return false;
  53. }
  54. // Returns if there is any word in the trie
  55. // that starts with the given prefix.
  56. public boolean startsWith(String prefix) {
  57. HashMap<Character, TrieNode> children = root.children;
  58. for (int i = 0; i < prefix.length(); i++) {
  59. char c = prefix.charAt(i);
  60. if (!children.containsKey(c)) {
  61. return false;
  62. }
  63. if (i == prefix.length() - 1) {
  64. return true;
  65. }
  66. children = children.get(c).children;
  67. }
  68. // useless
  69. return false;
  70. }
  71. }
  72. // Your Trie object will be instantiated and called as such:
  73. // Trie trie = new Trie();
  74. // trie.insert("somestring");
  75. // trie.search("key");

Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.


本题是一个栈的操作,但是要求getMin()在O(1)的时间复杂度。

考虑使用另一个辅助栈,用来存储[0..i]的最小值。

  1. class MinStack {
  2. Stack<Integer> stack = new Stack<Integer>();
  3. Stack<Integer> min = new Stack<Integer>();
  4. public void push(int x) {
  5. if (stack.isEmpty()) {
  6. stack.push(x);
  7. min.push(x);
  8. } else {
  9. stack.push(x);
  10. min.push(Math.min(stack.peek(), min.peek()));
  11. }
  12. }
  13. public void pop() {
  14. if (!stack.isEmpty()) {
  15. stack.pop();
  16. min.pop();
  17. }
  18. }
  19. public int top() {
  20. if (!stack.isEmpty()) {
  21. return stack.peek();
  22. }
  23. throw new IllegalStateException();
  24. }
  25. public int getMin() {
  26. if (!min.isEmpty()) {
  27. return min.peek();
  28. }
  29. throw new IllegalStateException();
  30. }
  31. }

Peeking Iterator

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation -- it essentially peek() at the element that will be returned by the next call to next().


Here is an example. Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].

Call next() gets you 1, the first element in the list.

Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.

You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.

Hint:

  1. Think of "looking ahead". You want to cache the next element.
  2. Is one variable sufficient? Why or why not?
  3. Test your design with call order of peek() before next() vs next() before peek().
  4. For a clean implementation, check out Google's guava library source code.

Follow up: How would you extend your design to be generic and work with all types, not just integer?

Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.


peek的含义是,返回顶部元素,但是元素不弹出。但是返回顶部元素的时候,必定要使用next()。定义一个变量“缓存”元素即可。

  1. private Iterator<Integer> iterator;
  2. private boolean hasPeeked;
  3. private Integer peekedElement;
  4. public L284_Peeking_Iterator(Iterator<Integer> iterator) {
  5. // initialize any member here.
  6. this.iterator = iterator;
  7. }
  8. // Returns the next element in the iteration without advancing the iterator.
  9. public Integer peek() {
  10. if (!hasPeeked) {
  11. peekedElement = iterator.next();
  12. hasPeeked = true;
  13. }
  14. return peekedElement;
  15. }
  16. // hasNext() and next() should behave the same as in the Iterator interface.
  17. // Override them if needed.
  18. public Integer next() {
  19. if (!hasPeeked) {
  20. return iterator.next();
  21. }
  22. Integer result = peekedElement;
  23. hasPeeked = false;
  24. peekedElement = null;
  25. return result;
  26. }
  27. public boolean hasNext() {
  28. return hasPeeked || iterator.hasNext();
  29. }

Serialize and Deserialize Binary Tree

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

  1. 1
  2. / \
  3. 2 3
  4. / \
  5. 4 5

as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.


我的最开始的思路是:先求树的深度h,把树中的每个结点(2^h-1)个结点,全部记录下来,即使是null。但是这样有些极端的测试用例会超时,比如树中每个结点只有右结点,树高1000。用这种方法要遍历2^h-1次,显然能够优化。

参考 how LeetCode OJ serializes a binary tree的序列化方式,下面的二叉树,序列化后的String可以是”1,2,3,null,null,4,null,5,null”,这种方法在序列化二叉树时,只用树结点数量规模的字符即可,省时省空间。

  1. 1
  2. / \
  3. 2 3
  4. /
  5. 4
  6. /
  7. 5
  1. public String serialize(TreeNode root) {
  2. if (root == null) {
  3. return "";
  4. }
  5. StringBuffer sb = new StringBuffer();
  6. Deque<TreeNode> deque = new LinkedList<TreeNode>();
  7. deque.add(root);
  8. while (!deque.isEmpty()) {
  9. TreeNode p = deque.pop();
  10. if (p == null) {
  11. sb.append(",#");
  12. } else {
  13. sb.append("," + p.val);
  14. deque.add(p.left);
  15. deque.add(p.right);
  16. }
  17. }
  18. // 第一个元素前也有一个逗号,截取
  19. return sb.toString().substring(1);
  20. }
  21. public TreeNode deserialize(String data) {
  22. if (data == null || data.length() == 0) {
  23. return null;
  24. }
  25. String[] s = data.split(",");
  26. TreeNode[] node = new TreeNode[s.length];
  27. // 新建TreeNode,并初始化
  28. for (int i = 0; i < node.length; i++) {
  29. if (!"#".equals(s[i])) {
  30. node[i] = new TreeNode(Integer.valueOf(s[i]));
  31. }
  32. }
  33. int parent = 0;
  34. // 将结点连接起来
  35. for (int i = 0; parent * 2 + 2 < s.length; i++) {
  36. if (node[i] != null) {
  37. node[i].left = node[parent * 2 + 1];
  38. node[i].right = node[parent * 2 + 2];
  39. parent++;
  40. }
  41. }
  42. return node[0];
  43. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注