Ciel's blog

Hi, this is Ciel!

题目

输入一个链表,输出该链表中倒数第k个结点。

解题

队列的特性是:“先入先出”,栈的特性是:“先入后出”。

**push:**直接push进stack1。

**pop:**当stack2 中不为空时, 在stack2 中的栈顶元素是最先进入队列的元素, 直接弹出stack2栈顶元素;如果
stack2 为空时,我们把stack1中的元素逐个弹出并压入stack2,再弹出stack2栈顶元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Stack;

public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
stack1.push(node);
}

public int pop() {
if (stack2.empty()){
while (!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}

总结

  1. 相关题目:用两个队列实现一个栈。
  2. 不能只在if语句中return,因为可能无法进入循环而没有return,除非使用的有else。
  3. Java Stack 类

Stack类是一个后进先出(last in first out,LIFO)的堆栈,在Vector类的基础上扩展了5个方法。从源码(部分省略)看它提供的功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package java.util;

/**
* The {@code Stack} class represents a last-in-first-out
* (LIFO) stack of objects. It extends class {@code Vector} with five
* operations that allow a vector to be treated as a stack. The usual
* {@code push} and {@code pop} operations are provided, as well as a
* method to {@code peek} at the top item on the stack, a method to test
* for whether the stack is {@code empty}, and a method to {@code search}
* the stack for an item and discover how far it is from the top.
* <p>
* When a stack is first created, it contains no items.
*
* <p>A more complete and consistent set of LIFO stack operations is
* provided by the {@link Deque} interface and its implementations, which
* should be used in preference to this class. For example:
* <pre> {@code
* Deque<Integer> stack = new ArrayDeque<Integer>();}</pre>
*
* @author Jonathan Payne
* @since 1.0
*/
public
class Stack<E> extends Vector<E> {
/**
* Creates an empty Stack.
*/
public Stack() {
}

/**
* Pushes an item onto the top of this stack. This has exactly
* the same effect as:
* <blockquote><pre>
* addElement(item)</pre></blockquote>
*
* @param item the item to be pushed onto this stack.
* @return the {@code item} argument.
* @see java.util.Vector#addElement
*/
public E push(E item) {
addElement(item);

return item;
}

/**
* Removes the object at the top of this stack and returns that
* object as the value of this function.
*
* @return The object at the top of this stack (the last item
* of the {@code Vector} object).
* @throws EmptyStackException if this stack is empty.
*/
public synchronized E pop() {
E obj;
int len = size();

obj = peek();
removeElementAt(len - 1);

return obj;
}

/**
* Looks at the object at the top of this stack without removing it
* from the stack.
*
* @return the object at the top of this stack (the last item
* of the {@code Vector} object).
* @throws EmptyStackException if this stack is empty.
*/
public synchronized E peek() {
int len = size();

if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}

/**
* Tests if this stack is empty.
*
* @return {@code true} if and only if this stack contains
* no items; {@code false} otherwise.
*/
public boolean empty() {
return size() == 0;
}

/**
* Returns the 1-based position where an object is on this stack.
* If the object {@code o} occurs as an item in this stack, this
* method returns the distance from the top of the stack of the
* occurrence nearest the top of the stack; the topmost item on the
* stack is considered to be at distance {@code 1}. The {@code equals}
* method is used to compare {@code o} to the
* items in this stack.
*
* @param o the desired object.
* @return the 1-based position from the top of the stack where
* the object is located; the return value {@code -1}
* indicates that the object is not on the stack.
*/
public synchronized int search(Object o) {
int i = lastIndexOf(o);

if (i >= 0) {
return size() - i;
}
return -1;
}

/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = 1224463164541339165L;
}

references

《剑指offer》

“Missing return statement” within if / for / while

题目

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

解题

因为二叉树前序和中序遍历都有它的规律(在二叉树的前序遍历序列中,第一个数字总是树的根结点的值。在中序遍历序列中,根结点的值在序列的中间, 左子树的结点的值位于根结点的值的左边,而右子树的结点的值位于根结点的值的右边。),通过实例分析一下就可以找到。结合前序和中序遍历就可以找到二叉树的根结点和左右支。

而左支和右支的解决办法和圆二叉树相同,因而可以用递归的方法。

这道题思路还是出挺快的,但是自己就卡在了因为数据长度不可变而引起的一些bug上。我的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
// 排除非法输入
if (pre == null || in == null || pre.length != in.length){
return null;
}
// 这里要特别注意!!!
// 因为数组的不可变长的特性,下面在根据根结点创建存放左右支的时候,
// 若不存在左右支了,则可能创建长度为0的数组,不能用=null来判断,要用数组长度来判断
if (in.length == 0 || pre.length == 0 ){
return null;
}
TreeNode root = new TreeNode(pre[0]);
int rootIndex = 0;
int length = pre.length;
// 找到跟结点在中序遍历中的位置
for (int i=0; i<=length-1;i++){
if (in[i] == pre[0]){
rootIndex = i;
break;
}
}
// 根据节点位置,创建相应大小的数组存放根结点的左支和右支
int[] leftPre = new int [rootIndex];
int[] leftIn = new int [rootIndex];
int[] rightPre = new int [length-rootIndex-1];
int[] rightIn = new int [length-rootIndex-1];
// 遍历存放
for (int i=0; i<=length-1;i++){
if (i < rootIndex){
leftPre[i] = pre[i+1];
leftIn[i] = in[i];
} else if (i > rootIndex){
rightPre[i-1-rootIndex] = pre[i];
rightIn[i-1-rootIndex] = in[i];
}
}
// 递归,求左支&右支的根节点, and so on ..
root.left = reConstructBinaryTree(leftPre, leftIn);
root.right = reConstructBinaryTree(rightPre, rightIn);
return root;
}
}

牛客网上别人更高效的代码:(使用了Arrays.copyOfRange()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if (pre.length == 0 || in.length == 0) {
return null;
}
TreeNode root = new TreeNode(pre[0]);
// 在中序中找到前序的根
for (int i = 0; i < in.length; i++) {
if (in[i] == pre[0]) {
// 左子树,注意 copyOfRange 函数,左闭右开
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(in, 0, i));
// 右子树,注意 copyOfRange 函数,左闭右开
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, pre.length), Arrays.copyOfRange(in, i + 1, in.length));
break;
}
}
return root;
}
}

总结

  1. Arrays.copyOfRange()方法

copyOfRange是输入java.util包中的Arrays类的静态内部方法,可以被类直接调用。

1
Arrays.copyOfRange(T[ ] original,int from,int to)

将一个原始的数组original,从下标from开始复制,复制到上标to,生成一个新的数组。

  1. int[] myArray = new int[0];表示指向一个空的数组,而不是指向null。

References

牛客网讨论与题解

《剑指offer》

Java.util中的Arrays.copyOfRange方法的用法

[Why is int] a = new int[0]; allowed?

题目

在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

解题

从左下角/右上角开始寻找。如从左下角开始,当当前数值小于target时,向上部区域查找(向上移动一排);当当前数值大于target时,向右部区域查找(向右移动一列)。这样一行/一列地剔除数据,就会方便很多。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public boolean Find(int target, int [][] array) {
int cur_row = array.length-1;
int cur_col = 0;
while (cur_row >= 0 && cur_col < array[0].length){
if (target > array[cur_row][cur_col]){
cur_col += 1;
} else if (target < array[cur_row][cur_col]){
cur_row -= 1;
} else if (target == array[cur_row][cur_col]){
return true;
}
}
return false;
}
}

references

牛客网讨论与题解

0%