1、判断二叉树是否相同
bool is_same(Node *a, Node *b) {
return a?(b && b->val == a->val && is_same(a->left, b->left) && is_same(a->right, b->right)) : (b == 0);
}
2、(排列判断)整数数组,返回从1开始第一个不在数组中得整数?
把A[i]换到A[A[i] – 1]的位置即可
int i;
for (i = 0;i < n;) {
if ((A[i] > 0) && (A[i] <= n) && (A[A[i] - 1] != A[i])) {
int t = A[A[i] - 1];
A[A[i] - 1] = A[i];
A[i] = t;
} else {
++ i;
}
}
for (i = 0; i < n; ++i) {
if (A[i] != i + 1) {
return i + 1;
}
}
return n + 1
3、快速的复制文件
public class CopyFile {
private static void copyFileNio(final File from, final File to) throws IOException {
final RandomAccessFile inFile = new RandomAccessFile(from, "r");
try {
final RandomAccessFile outFile = new RandomAccessFile (to, "w");
try {
final FileChannel inChannel = inFile.getChannel();
final FileChannel outChannel = outFile.getChannel();
long pos = 0;
long toCopy = inFile.length();
while (toCopy > 0) {
final long bytes = inChannel.transferTo(pos, toCopy, outChannel);
pos += bytes;
toCopy -= bytes;
}
} finally {
outFile.close();
}
} finally {
inFile.close();
}
}
}
4、翻转句子i中单词的顺序
题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。不允许用java提供的类库。
例如输入“I am a student.”,则输出“student. a am I”。
分析:由于本题需要翻转句子,我们先颠倒句子中的所有字符。这时,不但翻转了句子中单词的顺序,而且单词内字符也被翻转了。我们再颠倒每个单词内的字符。由于单词内的字符被翻转两次,因此顺序仍然和输入时的顺序保持一致。
还是以上面的输入为例子。翻转“I am a student.”中所有字符得到“.tneduts a ma I”,再翻转每个单词中字符的顺序得到“students. a am I”,正是符合要求的输出。
public class Reverse {
private void reverse(char[] src, int start, int end) {
while (start < end) {
char temp = src[start];
src[start] = src[end];
src[end] = temp;
start ++;
end --;
}
}
private void reverseWord(char[] sentense) {
int i = 0;
int start = 0;
while(i < sentense.length) {
if (sentense[i] != ' ') {
i ++;
} else {
reverse(sentense, start, i);
start = i + 1;
}
}
}
public static void main(String[] argv) {
char[] centense = {'i',' ', 'l', 'o', 'v', 'e', ' ', 'y', 'o', 'u'};
Reverse r = new Reverse();
r.reverse(centense, 0 , centense.length - 1);
System.out.println(centense);
r.reverseWord(centense);
System.out.println(centense);
}
}