剑指Offer——编程题的Java实现

来源:互联网 发布:iphone6s usb共享网络 编辑:程序博客网 时间:2024/06/18 17:12

声明:我写这个的意图是我在看书的过程中,就我掌握的内容做一个笔记,没有抄袭的意图。再次说明一下,我找工作的过程中并不顺利,没有像那些牛人们拿到一大把的Offer,我只是希望通过我自己的努力,不断提高自己。想要真正掌握这些还是得买本书好好读一下。

注:还没有完结,先放出来,不断更新

1、面试题3:二维数组中的查找

题目大致为:

    一个二维数组,每一行按照从左到右递增,每一列按照从上到下递增,查找数组中是否存在某个数。如数组:

1  2  8    9

2  4  9   12

4  7  10  13

6  8  11  15

思路:

    这道题有其特殊性,从右上角或者左下角开始查找的方向是确定的。这句话是说比如是查找7,我们从右上角开始,9大于7,则减少列下标,查找13的话就增加行下表,查找的方向是确定的,这样就容易实现了。

Java代码:

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题3:二维数组的查找 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item03 {  
  10.     public static void main(String args[]) {  
  11.         // 测试用的例子  
  12.         int A[][] = { { 1289 }, { 24912 }, { 471013 },  
  13.                 { 681115 } };  
  14.         System.out.println(find(A, 7));  
  15.     }  
  16.       
  17.     /** 
  18.      * 二维数组的查找 
  19.      * @param array 已知的数组 
  20.      * @param number 待查找的数 
  21.      * @return 
  22.      */  
  23.     public static boolean find(int array[][], int number) {  
  24.         boolean flag = false;  
  25.         int rows = array.length;// 行数  
  26.         int columns = array[0].length;// 列数  
  27.         int row = 0;  
  28.         int column = columns - 1;  
  29.         while (row < rows && column >= 0) {  
  30.             // 比较二维数组中的元素与number的关系  
  31.             if (array[row][column] == number) {  
  32.                 flag = true;  
  33.                 break;// 跳出循环  
  34.             } else if (array[row][column] > number) {  
  35.                 // 列变小  
  36.                 column--;  
  37.             } else {  
  38.                 // 行变大  
  39.                 row++;  
  40.             }  
  41.         }  
  42.         return flag;  
  43.     }  
  44. }  


2、面试题4:替换空格

题目大致为:

    实现一个函数,把字符串中的每个空格替换成"%20"。

思路:

    在Java和C中,对字符串的处理略有不同,在C中字符串是以字符数组的形式存储的,并且在字符串或者字符数组中都有一个结束符"\0";而在Java中,却没有这样的结束符,所以本题在Java下的处理与C中也不一样。

    在C中,思路为:先遍历一遍,找到空格的个数,这样便可以计算新的字符串的长度=旧的字符串的长度+空格数*2,然后从尾部向前遍历,遇到非空格,则复制到新的位置,否则直接添加新字符。

    在Java中,字符替换主要有两种:replace(char oldChar, char newChar)replaceAll(String regex, String replacement)。

为简单起见,我加了点限制条件,用Java实现本题。

Java实现

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题4:替换空格 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item04 {  
  10.     public static void main(String args[]) {  
  11.         String s = "We are happy.";  
  12.         char c_old[] = s.toCharArray();  
  13.         // 为简单起见,我们假设给它一个新的空间,空间的大小组以存下替换后的字符  
  14.         char c_new[] = new char[100];  
  15.         for (int i = 0; i < c_old.length; i++) {  
  16.             c_new[i] = c_old[i];  
  17.         }  
  18.   
  19.         // 输出新的数组  
  20.         System.out.println(replaceBlank(c_new, c_old.length));  
  21.     }  
  22.       
  23.     /** 
  24.      * 计算新的字符串 
  25.      * @param c带空格的字符数组 
  26.      * @param length是指第一个字符到最后一个字符的长度,不是字符数组的长度 
  27.      * @return 
  28.      */  
  29.     public static String replaceBlank(char c[], int length) {  
  30.         // 查找空格的数目  
  31.         int blank = 0;  
  32.         for (int i = 0; i < length; i++) {  
  33.             if (c[i] == ' ') {  
  34.                 blank++;  
  35.             }  
  36.         }  
  37.   
  38.         // 重新计算新的数组的大小  
  39.         int length_new = length + blank * 2;  
  40.   
  41.         // 从尾到头查找  
  42.         int j = length - 1;  
  43.         int k = length_new - 1;  
  44.         while (j >= 0 && k >= 0) {  
  45.             if (c[j] != ' ') {  
  46.                 c[k--] = c[j];  
  47.             } else {  
  48.                 c[k--] = '0';  
  49.                 c[k--] = '2';  
  50.                 c[k--] = '%';  
  51.             }  
  52.             j--;  
  53.         }  
  54.         return new String(c);  
  55.     }  
  56. }  

3、面试题5:从尾到头打印链表

题目大致为:

    输入一个链表的头结点,从未到头反过来打印每个结点的值。

思路:

    题目的要求是进行从尾到头输出,而链表的查找只能是顺序查找,栈的结构满足这样的条件:先进后出。同样,也可以使用递归的方式求解。

Java代码:

链表类:

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 链表的节点 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class ListNode {  
  10.     private int value;  
  11.     private ListNode next;  
  12.   
  13.     public ListNode(int value) {  
  14.         this.value = value;  
  15.     }  
  16.   
  17.     public ListNode(int value, ListNode next) {  
  18.         this.value = value;  
  19.         this.next = next;  
  20.     }  
  21.   
  22.     public void setValue(int value) {  
  23.         this.value = value;  
  24.     }  
  25.   
  26.     public void setNext(ListNode next) {  
  27.         this.next = next;  
  28.     }  
  29.   
  30.     public int getValue() {  
  31.         return this.value;  
  32.     }  
  33.   
  34.     public ListNode getNext() {  
  35.         return this.next;  
  36.     }  
  37.   
  38. }  


Java实现:

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. import java.util.Stack;  
  4.   
  5. /** 
  6.  * 面试题5:从尾到头打印链表 
  7.  *  
  8.  * @author dell 
  9.  *  
  10.  */  
  11. public class Item05 {  
  12.     /** 
  13.      * 测试 
  14.      *  
  15.      * @param args 
  16.      */  
  17.     public static void main(String args[]) {  
  18.         // 构建链表  
  19.         ListNode head = new ListNode(0);  
  20.         ListNode node_one = new ListNode(1);  
  21.         ListNode node_two = new ListNode(2);  
  22.         ListNode node_three = new ListNode(3);  
  23.         ListNode node_four = new ListNode(4);  
  24.         head.setNext(node_one);  
  25.         node_one.setNext(node_two);  
  26.         node_two.setNext(node_three);  
  27.         node_three.setNext(node_four);  
  28.         node_four.setNext(null);  
  29.         System.out.println("第一种方式,递归实现:");  
  30.         printListReverse_1(head);  
  31.         //换行  
  32.         System.out.println();  
  33.         System.out.println("第二种方式,非递归实现:");  
  34.         printListReverse_2(head);  
  35.     }  
  36.   
  37.     /** 
  38.      * 用递归实现 
  39.      *  
  40.      * @param head 
  41.      */  
  42.     public static void printListReverse_1(ListNode head) {  
  43.         if (head != null) {  
  44.             if (head.getNext() != null) {  
  45.                 printListReverse_1(head.getNext());  
  46.             }  
  47.             System.out.print(head.getValue() + "、");  
  48.         }  
  49.     }  
  50.   
  51.     /** 
  52.      * 用栈实现 
  53.      *  
  54.      * @param head 
  55.      */  
  56.     public static void printListReverse_2(ListNode head) {  
  57.         Stack<Integer> s = new Stack<Integer>();  
  58.         ListNode p = head;  
  59.         // 进栈  
  60.         while (p != null) {  
  61.             s.push(p.getValue());  
  62.             p = p.getNext();  
  63.         }  
  64.   
  65.         // 出栈  
  66.         while (!s.isEmpty()) {  
  67.             System.out.print(s.pop() + "、");  
  68.         }  
  69.         System.out.println();  
  70.     }  
  71. }  


4、面试题6:重建二叉树

题目大致为:

    已知前序遍历序列和中序遍历序列,要求重建二叉树

二叉树的结点定义:

 

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. public class BinaryTreeNode {  
  4.     private int value;  
  5.     private BinaryTreeNode left;  
  6.     private BinaryTreeNode right;  
  7.   
  8.     public BinaryTreeNode(int value) {  
  9.         this.value = value;  
  10.     }  
  11.   
  12.     public BinaryTreeNode(int value, BinaryTreeNode left, BinaryTreeNode right) {  
  13.         this.value = value;  
  14.         this.left = left;  
  15.         this.right = right;  
  16.     }  
  17.   
  18.     public int getValue() {  
  19.         return value;  
  20.     }  
  21.   
  22.     public void setValue(int value) {  
  23.         this.value = value;  
  24.     }  
  25.   
  26.     public BinaryTreeNode getLeft() {  
  27.         return left;  
  28.     }  
  29.   
  30.     public void setLeft(BinaryTreeNode left) {  
  31.         this.left = left;  
  32.     }  
  33.   
  34.     public BinaryTreeNode getRight() {  
  35.         return right;  
  36.     }  
  37.   
  38.     public void setRight(BinaryTreeNode right) {  
  39.         this.right = right;  
  40.     }  
  41.   
  42. }  

思路:

    如上图所示,在前序遍历的序列中第一个就是树的根结点,此时再在中序遍历的序列里查找这个根结点,则中序遍历的序列里根结点左侧的就是左子树,右侧的就是右子树,再对左右子树进行同样的操作,此时可以使用递归实现,这样便能构造出这个二叉树。

Java代码:

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题6:重建二叉树 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item06 {  
  10.     public static void main(String args[]) {  
  11.         // 二叉树的前序遍历  
  12.         int preOrder[] = { 12473568 };  
  13.         // 二叉树的中序遍历  
  14.         int inOrder[] = { 47215386 };  
  15.           
  16.         BinaryTreeNode root = constructTree(preOrder, inOrder);  
  17.         printPostOrder(root);  
  18.     }  
  19.   
  20.     public static BinaryTreeNode constructTree(int preOrder[], int inOrder[]) {  
  21.         // 根据前序遍历创建根结点  
  22.         BinaryTreeNode root = new BinaryTreeNode(preOrder[0]);  
  23.         root.setLeft(null);  
  24.         root.setRight(null);  
  25.   
  26.         int leftNum = 0;//左子树的结点个数  
  27.   
  28.         // 在中序中找到根节点  
  29.         for (int i = 0; i < inOrder.length; i++) {  
  30.             if (inOrder[i] == root.getValue()) {  
  31.                 break;  
  32.             } else {  
  33.                 leftNum++;  
  34.             }  
  35.         }  
  36.         int rightNum = preOrder.length - 1 - leftNum;  
  37.   
  38.         // 左子树不为空  
  39.         if (leftNum > 0) {  
  40.             //构造左子树的前序和中序遍历序列  
  41.             int leftPreOrder[] = new int[leftNum];  
  42.             int leftInOrder[] = new int[leftNum];  
  43.             for (int i = 0; i < leftNum; i++) {  
  44.                 leftPreOrder[i] = preOrder[i + 1];  
  45.                 leftInOrder[i] = inOrder[i];  
  46.             }  
  47.             //递归构造左子树  
  48.             BinaryTreeNode leftRoot = constructTree(leftPreOrder, leftInOrder);  
  49.             root.setLeft(leftRoot);  
  50.         }  
  51.           
  52.         //右子树不为空  
  53.         if (rightNum > 0) {  
  54.             //构造右子树的前序和中序遍历序列  
  55.             int rightPreOrder[] = new int[rightNum];  
  56.             int rightInOrder[] = new int[rightNum];  
  57.             for (int i = 0; i < rightNum; i++) {  
  58.                 rightPreOrder[i] = preOrder[leftNum + i + 1];  
  59.                 rightInOrder[i] = inOrder[leftNum + i + 1];  
  60.             }  
  61.             //递归构造右子树  
  62.             BinaryTreeNode rightRoot = constructTree(rightPreOrder,  
  63.                     rightInOrder);    
  64.             root.setRight(rightRoot);  
  65.         }  
  66.         return root;  
  67.     }  
  68.       
  69.     /** 
  70.      * 二叉树的后序遍历(递归实现) 
  71.      * @param root 树的根结点 
  72.      */  
  73.     public static void printPostOrder(BinaryTreeNode root) {  
  74.         if (root != null) {  
  75.             printPostOrder(root.getLeft());  
  76.             printPostOrder(root.getRight());  
  77.             System.out.print(root.getValue() + "、");  
  78.         }  
  79.     }  
  80. }  


面试题7:用两个栈实现队列

题目大致为:

    用两个栈实现队列的两个函数appendTaildeleteHead。

思路:

    栈的特性是:后进先出,而队列的特性是:先进先出。这里使用两个栈实现队列有点负负得正的意思。栈1负责添加,而栈2负责删除。

Java代码:

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. import java.util.Stack;  
  4.   
  5. /** 
  6.  * 面试题7:用两个栈实现队列 
  7.  *  
  8.  * @author dell 
  9.  *  
  10.  */  
  11.   
  12. /** 
  13.  * 构造一个类 
  14.  *  
  15.  * @author dell 
  16.  *  
  17.  * @param <T>泛型 
  18.  */  
  19. class CQueue<T> {  
  20.     // 两个栈  
  21.     private Stack<T> stack1;  
  22.     private Stack<T> stack2;  
  23.   
  24.     public CQueue() {  
  25.         this.stack1 = new Stack<T>();  
  26.         this.stack2 = new Stack<T>();  
  27.     }  
  28.   
  29.     /** 
  30.      * 模拟在队列末尾插入 
  31.      *  
  32.      * @param node 
  33.      */  
  34.     public void appendTail(T node) {  
  35.         stack1.push(node);  
  36.     }  
  37.   
  38.     /** 
  39.      * 模拟删除队列的头 
  40.      *  
  41.      * @return 
  42.      */  
  43.     public T deleteHead() {  
  44.         if (stack2.size() == 0) {  
  45.             if (stack1.size() == 0) {  
  46.                 try {  
  47.                     throw new Exception("队列为空");  
  48.                 } catch (Exception e) {  
  49.                     // TODO Auto-generated catch block  
  50.                     e.printStackTrace();  
  51.                 }  
  52.             }  
  53.             // stack1 不为空,将stack1中的元素放入stack2中  
  54.             while (stack1.size() > 0) {  
  55.                 stack2.push(stack1.pop());  
  56.             }  
  57.         }  
  58.         return stack2.pop();  
  59.     }  
  60. }  
  61.   
  62. public class Item07 {  
  63.   
  64.     // 测试  
  65.     public static void main(String args[]) {  
  66.         // 在队列中增加元素  
  67.         CQueue<Integer> cq = new CQueue<Integer>();  
  68.         for (int i = 0; i < 5; i++) {  
  69.             cq.appendTail(i);  
  70.         }  
  71.         // 依次取出  
  72.         for (int i = 0; i < 5; i++) {  
  73.             System.out.print(cq.deleteHead() + "、");  
  74.         }  
  75.         System.out.println();  
  76.         // 此时为空,再取一次,看会不会报错  
  77.         cq.deleteHead();  
  78.     }  
  79. }  


面试题8:旋转数组的最小数字

题目大致为:

    一个递增排序的数组的一个旋转(把一个数组最开始的若干元素搬到数组的末尾,称之为数组的旋转),输出旋转数组的最小元素。

思路:

    其实旋转过后的数组是部分有序的,这样的数组依然可以使用折半查找的思路求解

Java代码:

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题8:旋转数组的最小数字 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item08 {  
  10.     public static void main(String args[]) {  
  11.         int A[] = { 34512 };// 数组A是数组{1,2,3,4,5}的旋转数组  
  12.         System.out.println(findMin(A));  
  13.     }  
  14.   
  15.     public static int findMin(int array[]) {  
  16.         int low = 0;  
  17.         int high = array.length - 1;  
  18.         int middle = low;  
  19.   
  20.         while (array[low] >= array[high]) {  
  21.             // 数组中就只有两个数,最小的为后者  
  22.             if (high - low == 1) {  
  23.                 middle = high;  
  24.                 break;  
  25.             }  
  26.             // 查找中间位置  
  27.             middle = (high + low) / 2;  
  28.             if (array[middle] >= array[low]) {  
  29.                 low = middle;  
  30.             } else if (array[middle] <= array[high]) {  
  31.                 high = middle;  
  32.             }  
  33.         }  
  34.         return array[middle];  
  35.     }  
  36. }  


面试题9:斐波那契数列

    菲波那切数列是每一个学C语言的人都特别熟悉的一个问题。

思路:

    用递归实现的过程中会出现重复计算的情况,此时,可以利用动态规划的思想,保存中间结果,这样可以避免不必要的计算。

Java代码:

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题9:斐波那契数列 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item09 {  
  10.     public static void main(String args[]) {  
  11.         int n = 3;  
  12.         System.out.println(fibonacci(n));  
  13.     }  
  14.   
  15.     public static int fibonacci(int n) {  
  16.         if (n == 0) {  
  17.             return 0;  
  18.         } else if (n == 1) {  
  19.             return 1;  
  20.         } else {  
  21.             //由zero和one保存中间结果  
  22.             int zero = 0;  
  23.             int one = 1;  
  24.             int fN = 0;  
  25.             for (int i = 2; i <= n; i++) {  
  26.                 fN = one + zero;  
  27.                 zero = one;  
  28.                 one = fN;  
  29.             }  
  30.             return fN;  
  31.         }  
  32.     }  
  33. }  


面试题10:二进制中1的个数

题目大致为:
    实现一个函数,输入一个整数,输出该数二进制表示中1的个数。
思路:
    把一个整数减去1,再和原整数做与运算,会把最右边一个1编程0,那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作。
Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题10:二进制中1的个数 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item10 {  
  10.     public static void main(String args[]) {  
  11.   
  12.         int n = 9;  
  13.         System.out.println("9的二进制表示中1的个数为:" + numberOf1(n));  
  14.   
  15.     }  
  16.       
  17.     /** 
  18.      * 利用了与的操作 
  19.      * @param n 
  20.      * @return 
  21.      */  
  22.     public static int numberOf1(int n) {  
  23.         int count = 0;  
  24.   
  25.         while (n != 0) {  
  26.             count++;  
  27.             n = (n - 1) & n;  
  28.         }  
  29.   
  30.         return count;  
  31.     }  
  32.   
  33. }  

面试题11:数值的整数次方

题目大致为:
    实现函数double power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
思路:
    可以考虑对指数折半,这样只需要计算一半的值,若指数是奇数,则-1再折半,否则直接折半。
Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题11:数值的整数次方 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item11 {  
  10.     public static void main(String args[]) {  
  11.         int base = 2;  
  12.         int exponent_1 = 9;  
  13.         int exponent_2 = 10;  
  14.         System.out.println("当exponent为奇数:" + power(base, exponent_1));  
  15.         System.out.println("当exponent为偶数:" + power(base, exponent_2));  
  16.     }  
  17.   
  18.     /** 
  19.      * 整数次方 
  20.      *  
  21.      * @param base底 
  22.      * @param exponent指数 
  23.      * @return 
  24.      */  
  25.     public static double power(double base, int exponent) {  
  26.         if (exponent == 0) {  
  27.             return 1;  
  28.         }  
  29.   
  30.         if (exponent == 1) {  
  31.             return base;  
  32.         }  
  33.         if (exponent >> 1 == 0) {// 偶数  
  34.             int exponent_1 = exponent >> 1;  
  35.             double tmp = power(base, exponent_1);  
  36.             return tmp * tmp;  
  37.         } else {// 非偶数  
  38.             int exponent_2 = exponent - 1;// -1后就是偶数  
  39.             double tmp = power(base, exponent_2);  
  40.             return tmp * base;// 最后还有先开始减掉的一个base  
  41.         }  
  42.     }  
  43. }  

面试题12:打印1到最大的n位数

面试题13:在O(1)时间删除链表结点

题目大致为:
    给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点。
思路:
    想要在O(1)时间内删除链表的指定结点,要遍历的话得O(n),则肯定不能遍历。若是要删除的结点不是尾结点,那么可以将后面的那个值复制到该指针处,并将后面指针所指空间删除,用复制+删除后面的实现删除,时间复杂度为O(1)。对于尾结点,需要遍历,那么时间复杂度是O(n),但是总的时间复杂度为[(n-1)*O(1)+O(n)]/n,结果是O(1)
链表结构:
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 链表的节点 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class ListNode {  
  10.     private int value;  
  11.     private ListNode next;  
  12.   
  13.     public ListNode(int value) {  
  14.         this.value = value;  
  15.     }  
  16.   
  17.     public ListNode(int value, ListNode next) {  
  18.         this.value = value;  
  19.         this.next = next;  
  20.     }  
  21.   
  22.     public void setValue(int value) {  
  23.         this.value = value;  
  24.     }  
  25.   
  26.     public void setNext(ListNode next) {  
  27.         this.next = next;  
  28.     }  
  29.   
  30.     public int getValue() {  
  31.         return this.value;  
  32.     }  
  33.   
  34.     public ListNode getNext() {  
  35.         return this.next;  
  36.     }  
  37.   
  38. }  

Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题13:在O(1)时间删除链表的节点 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item13 {  
  10.     public static void main(String args[]) {  
  11.         // 构建链表  
  12.         ListNode head = new ListNode(1);  
  13.         ListNode node_2 = new ListNode(2);  
  14.         ListNode node_3 = new ListNode(3);  
  15.         ListNode node_4 = new ListNode(4);  
  16.         ListNode node_5 = new ListNode(5);  
  17.         ListNode node_6 = new ListNode(6);  
  18.         ListNode node_7 = new ListNode(7);  
  19.         head.setNext(node_2);  
  20.         node_2.setNext(node_3);  
  21.         node_3.setNext(node_4);  
  22.         node_4.setNext(node_5);  
  23.         node_5.setNext(node_6);  
  24.         node_6.setNext(node_7);  
  25.         node_7.setNext(null);  
  26.   
  27.         // 输出原始链表  
  28.         System.out.println("原始链表:");  
  29.         printList(head);  
  30.         System.out.println("----------------");  
  31.   
  32.         // 删除结点node_3  
  33.         deleteNode(head, node_3);  
  34.         System.out.println("删除node_3后链表:");  
  35.         printList(head);  
  36.         System.out.println("----------------");  
  37.   
  38.         // 删除结点head  
  39.         deleteNode(head, head);  
  40.         System.out.println("删除head后链表:");  
  41.         printList(head);  
  42.         System.out.println("----------------");  
  43.     }  
  44.   
  45.     /** 
  46.      * 狸猫换太子删除结点 
  47.      *  
  48.      * @param head头指针 
  49.      * @param toBeDeleted要删除的指针 
  50.      */  
  51.     public static void deleteNode(ListNode head, ListNode toBeDeleted) {  
  52.         if (head == null || toBeDeleted == null) {  
  53.             return;  
  54.         }  
  55.   
  56.         // 找到要删除的节点的下一个节点  
  57.         if (toBeDeleted.getNext() != null) {  
  58.             ListNode p = toBeDeleted.getNext();// p为toBeDeleted的下一个节点  
  59.             toBeDeleted.setValue(p.getValue());  
  60.             // 删除p节点  
  61.             toBeDeleted.setNext(p.getNext());  
  62.         } else if (head == toBeDeleted) {  
  63.             // 如果头结点就是要删除的节点  
  64.             head = null;  
  65.         } else {  
  66.             // 删除尾节点  
  67.             ListNode currentNode = head;// 用于遍历链表  
  68.             while (currentNode.getNext() != toBeDeleted) {  
  69.                 currentNode = currentNode.getNext();  
  70.             }  
  71.             currentNode.setNext(null);  
  72.         }  
  73.     }  
  74.   
  75.     /** 
  76.      * 打印链表 
  77.      *  
  78.      * @param head头指针 
  79.      */  
  80.     public static void printList(ListNode head) {  
  81.         ListNode current = head;  
  82.         while (current != null) {  
  83.             System.out.print(current.getValue() + "、");  
  84.             current = current.getNext();  
  85.         }  
  86.         System.out.println();  
  87.     }  
  88. }  

面试题14:调整数组顺序使奇数位于偶数前面

题目大致为:

    对于一个数组,实现一个函数使得所有奇数位于数组的前半部分,偶数位于数组的后半部分。

思路:

    可以使用双指针的方式,一个指针指向数组的开始,一个指针指向数组的尾部,如果头部的数为偶数且尾部的数是奇数则交换,否则头部指针向后移动,尾部指针向前移动,直到两个指针相遇

Java代码:

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. import java.util.Arrays;  
  4.   
  5. /** 
  6.  * 面试题14:调整数组顺序使奇数位于偶数前面 
  7.  *  
  8.  * @author dell 
  9.  *  
  10.  */  
  11. public class Item14 {  
  12.     public static void main(String args[]) {  
  13.         int A[] = { 12345 };  
  14.         rejustArray(A);  
  15.         System.out.println(Arrays.toString(A));  
  16.     }  
  17.       
  18.     /** 
  19.      * 调整数组的顺序 
  20.      * @param array 数组 
  21.      */  
  22.     public static void rejustArray(int array[]) {  
  23.         // 两个位置,头和尾  
  24.         int low = 0;  
  25.         int high = array.length - 1;  
  26.   
  27.         // 两个位置直到相遇  
  28.         while (low < high) {  
  29.             // 如果low位置上的为偶数,high位置上的为奇数,交换  
  30.             if (array[low] % 2 == 0 && array[high] % 2 == 1) {  
  31.                 int tmp = array[low];  
  32.                 array[low] = array[high];  
  33.                 array[high] = tmp;  
  34.                 low++;  
  35.                 high--;  
  36.             } else if (array[low] % 2 == 1) {// 如果low位置上的为奇数,low后移  
  37.                 low++;  
  38.             } else {// high位置上的为偶数,high前移  
  39.                 high--;  
  40.             }  
  41.         }  
  42.   
  43.     }  
  44.   
  45. }  

面试题15:链表中倒数第k个结点

题目大致为:

    在一个链表中,查找倒数的第k个数。

思路:

    使用双指针的方式,前一个指针先走k步(中间隔k-1个结点),后一个指针才开始走,直到第一个指针走到尾,后一个指针指向的就是要找的倒数第k个数。值得注意的是:1、k是否超过链表长度且k必须为正整数;2、链表是否为空。

链表结构

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 链表的节点 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class ListNode {  
  10.     private int value;  
  11.     private ListNode next;  
  12.   
  13.     public ListNode(int value) {  
  14.         this.value = value;  
  15.     }  
  16.   
  17.     public ListNode(int value, ListNode next) {  
  18.         this.value = value;  
  19.         this.next = next;  
  20.     }  
  21.   
  22.     public void setValue(int value) {  
  23.         this.value = value;  
  24.     }  
  25.   
  26.     public void setNext(ListNode next) {  
  27.         this.next = next;  
  28.     }  
  29.   
  30.     public int getValue() {  
  31.         return this.value;  
  32.     }  
  33.   
  34.     public ListNode getNext() {  
  35.         return this.next;  
  36.     }  
  37.   
  38. }  

Java代码:

[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题15:链表中倒数第k个结点 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item15 {  
  10.   
  11.     public static void main(String args[]) {  
  12.         // 构建链表  
  13.         ListNode head = new ListNode(1);  
  14.         ListNode h1 = new ListNode(2);  
  15.         ListNode h2 = new ListNode(3);  
  16.         ListNode h3 = new ListNode(4);  
  17.         ListNode h4 = new ListNode(5);  
  18.         ListNode h5 = new ListNode(6);  
  19.         head.setNext(h1);  
  20.         h1.setNext(h2);  
  21.         h2.setNext(h3);  
  22.         h3.setNext(h4);  
  23.         h4.setNext(h5);  
  24.         h5.setNext(null);  
  25.         // 查找倒数第k个  
  26.         ListNode p = findKthToTail(head, 3);  
  27.         System.out.println(p.getValue());  
  28.   
  29.     }  
  30.   
  31.     public static ListNode findKthToTail(ListNode head, int k) {  
  32.         // 首先判断链表是否存在,k是否大于0  
  33.         if (head == null || k <= 0) {  
  34.             return null;  
  35.         }  
  36.   
  37.         ListNode prePoint = head;// 第一个指针  
  38.         ListNode postPoint = head;// 第二个指针  
  39.   
  40.         for (int i = 0; i < k - 1; i++) {  
  41.             if (prePoint.getNext() != null) {  
  42.                 prePoint = prePoint.getNext();  
  43.             } else {  
  44.                 return null;  
  45.             }  
  46.         }  
  47.   
  48.         while (prePoint.getNext() != null) {  
  49.             prePoint = prePoint.getNext();  
  50.             postPoint = postPoint.getNext();  
  51.         }  
  52.         return postPoint;  
  53.   
  54.     }  
  55.   
  56. }  

面试题16:反转链表

题目大致为:
    对于一个链表,反转该链表并返回头结点。
思路:
    主要是指针的操作,但是要注意不能断链。这里可以使用非递归的方式求解。
链表结构
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 链表的节点 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class ListNode {  
  10.     private int value;  
  11.     private ListNode next;  
  12.   
  13.     public ListNode(int value) {  
  14.         this.value = value;  
  15.     }  
  16.   
  17.     public ListNode(int value, ListNode next) {  
  18.         this.value = value;  
  19.         this.next = next;  
  20.     }  
  21.   
  22.     public void setValue(int value) {  
  23.         this.value = value;  
  24.     }  
  25.   
  26.     public void setNext(ListNode next) {  
  27.         this.next = next;  
  28.     }  
  29.   
  30.     public int getValue() {  
  31.         return this.value;  
  32.     }  
  33.   
  34.     public ListNode getNext() {  
  35.         return this.next;  
  36.     }  
  37.   
  38. }  

Java代码:
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题16:反转链表 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item16 {  
  10.     /** 
  11.      * 测试函数 
  12.      *  
  13.      * @param args 
  14.      */  
  15.     public static void main(String args[]) {  
  16.         // 构建链表  
  17.         ListNode head = new ListNode(0);  
  18.         ListNode node_one = new ListNode(1);  
  19.         ListNode node_two = new ListNode(2);  
  20.         ListNode node_three = new ListNode(3);  
  21.         ListNode node_four = new ListNode(4);  
  22.         head.setNext(node_one);  
  23.         node_one.setNext(node_two);  
  24.         node_two.setNext(node_three);  
  25.         node_three.setNext(node_four);  
  26.         node_four.setNext(null);  
  27.         // 打印  
  28.         ListNode reservedHead = reverseList(head);  
  29.         ListNode tmp = reservedHead;  
  30.         while (tmp != null) {  
  31.             System.out.print(tmp.getValue() + "、");  
  32.             tmp = tmp.getNext();  
  33.         }  
  34.     }  
  35.   
  36.     /** 
  37.      * 非递归实现 
  38.      *  
  39.      * @param head头指针 
  40.      * @return 
  41.      */  
  42.     public static ListNode reverseList(ListNode head) {  
  43.         ListNode reservedHead = null;  
  44.         ListNode pNode = head;  
  45.         ListNode pPrev = null;  
  46.         while (pNode != null) {  
  47.             ListNode pNext = pNode.getNext();  
  48.   
  49.             if (pNext == null) {  
  50.                 reservedHead = pNode;  
  51.             }  
  52.   
  53.             pNode.setNext(pPrev);  
  54.             pPrev = pNode;  
  55.             pNode = pNext;  
  56.         }  
  57.         return reservedHead;  
  58.     }  
  59. }  

面试题17:合并两个排序的链表

题目大致为:
输入两个递增排序的链表,合并这两个链表并使得新链表中的结点仍然按照递增排序的。
思路:
主要是链表中值的比较,取较小的结点插入到新的链表中。
链表结构
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 链表的节点 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class ListNode {  
  10.     private int value;  
  11.     private ListNode next;  
  12.   
  13.     public ListNode(int value) {  
  14.         this.value = value;  
  15.     }  
  16.   
  17.     public ListNode(int value, ListNode next) {  
  18.         this.value = value;  
  19.         this.next = next;  
  20.     }  
  21.   
  22.     public void setValue(int value) {  
  23.         this.value = value;  
  24.     }  
  25.   
  26.     public void setNext(ListNode next) {  
  27.         this.next = next;  
  28.     }  
  29.   
  30.     public int getValue() {  
  31.         return this.value;  
  32.     }  
  33.   
  34.     public ListNode getNext() {  
  35.         return this.next;  
  36.     }  
  37.   
  38. }  

Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题17:合并两个排序的链表 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item17 {  
  10.     public static void main(String args[]) {  
  11.         // 构建链表1  
  12.         ListNode head1 = new ListNode(1);  
  13.         ListNode node1_2 = new ListNode(3);  
  14.         ListNode node1_3 = new ListNode(5);  
  15.         ListNode node1_4 = new ListNode(7);  
  16.         head1.setNext(node1_2);  
  17.         node1_2.setNext(node1_3);  
  18.         node1_3.setNext(node1_4);  
  19.         node1_4.setNext(null);  
  20.         // 构建链表2  
  21.         ListNode head2 = new ListNode(2);  
  22.         ListNode node2_2 = new ListNode(4);  
  23.         ListNode node2_3 = new ListNode(6);  
  24.         ListNode node2_4 = new ListNode(8);  
  25.         head2.setNext(node2_2);  
  26.         node2_2.setNext(node2_3);  
  27.         node2_3.setNext(node2_4);  
  28.         node2_4.setNext(null);  
  29.   
  30.         System.out.println("链表1:");  
  31.         printList(head1);  
  32.         System.out.println("-------------");  
  33.   
  34.         System.out.println("链表2:");  
  35.         printList(head2);  
  36.         System.out.println("-------------");  
  37.   
  38.         System.out.println("合并后的链表:");  
  39.         ListNode head = mergeList(head1, head2);  
  40.         printList(head);  
  41.         System.out.println("-------------");  
  42.     }  
  43.       
  44.     /** 
  45.      * 合并两个链表 
  46.      * @param head1链表1 
  47.      * @param head2链表2 
  48.      * @return 
  49.      */  
  50.     public static ListNode mergeList(ListNode head1, ListNode head2) {  
  51.         ListNode head = null;// 合并后的头指针  
  52.   
  53.         // 如果有一个为空,则为另一个链表  
  54.         if (head1 == null) {  
  55.             head = head2;  
  56.         }  
  57.         if (head2 == null) {  
  58.             head = head1;  
  59.         }  
  60.   
  61.         // 两个都不为空  
  62.         if (head1 != null && head2 != null) {  
  63.             // node_1和node_2是用于遍历  
  64.             ListNode node_1 = head1;  
  65.             ListNode node_2 = head2;  
  66.             if (node_1.getValue() < node_2.getValue()) {  
  67.                 head = node_1;  
  68.                 head.setNext(mergeList(node_1.getNext(), node_2));  
  69.             } else {  
  70.                 head = node_2;  
  71.                 head.setNext(mergeList(node_1, node_2.getNext()));  
  72.             }  
  73.         }  
  74.         return head;  
  75.     }  
  76.   
  77.     /** 
  78.      * 打印链表 
  79.      *  
  80.      * @param head头指针 
  81.      */  
  82.     public static void printList(ListNode head) {  
  83.         ListNode current = head;  
  84.         while (current != null) {  
  85.             System.out.print(current.getValue() + "、");  
  86.             current = current.getNext();  
  87.         }  
  88.         System.out.println();  
  89.     }  
  90.   
  91. }  

面试题18:树的子结构

面试题19:二叉树的镜像

题目大致为:
    给定一棵二叉树,将其每一个结点的左右子树交换,这就叫做镜像。
思路:
    先对其根节点的左右子树处理,交换左右子树,此时再递归处理左右子树。这里要注意分为三种情况:1、树为空;2、只有根结点;3、左右子树至少有一个不为空。
Java实现:
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题19:二叉树的镜像 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item19 {  
  10.     public static void main(String args[]) {  
  11.         // 构建二叉树  
  12.         BinaryTreeNode root = new BinaryTreeNode(8);  
  13.         BinaryTreeNode t1 = new BinaryTreeNode(6);  
  14.         BinaryTreeNode t2 = new BinaryTreeNode(10);  
  15.         BinaryTreeNode t3 = new BinaryTreeNode(5);  
  16.         BinaryTreeNode t4 = new BinaryTreeNode(7);  
  17.         BinaryTreeNode t5 = new BinaryTreeNode(9);  
  18.         BinaryTreeNode t6 = new BinaryTreeNode(11);  
  19.         root.setLeft(t1);  
  20.         root.setRight(t2);  
  21.         t1.setLeft(t3);  
  22.         t1.setRight(t4);  
  23.         t2.setLeft(t5);  
  24.         t2.setRight(t6);  
  25.         t3.setLeft(null);  
  26.         t3.setRight(null);  
  27.         t4.setLeft(null);  
  28.         t4.setRight(null);  
  29.         t5.setLeft(null);  
  30.         t5.setRight(null);  
  31.         t6.setLeft(null);  
  32.         t6.setRight(null);  
  33.   
  34.         // 求镜像  
  35.         mirrorRecursively(root);  
  36.   
  37.         // 前序遍历输出  
  38.         printPreOrder(root);  
  39.     }  
  40.   
  41.     /** 
  42.      * 分三种情况:1、树为空;2、只有根结点;3、左右子树至少有一个不为空 对根结点的左右子树的处理方法与根结点的处理一致,可以采用递归的方式求解 
  43.      *  
  44.      * @param root 
  45.      */  
  46.     public static void mirrorRecursively(BinaryTreeNode root) {  
  47.         // 树为空  
  48.         if (root == null) {  
  49.             return;  
  50.         }  
  51.         // 只有一个根结点  
  52.         if (root.getLeft() == null && root.getRight() == null) {  
  53.             return;  
  54.         }  
  55.   
  56.         // 左右子树至少有一个不为空  
  57.         BinaryTreeNode treeTmp = root.getLeft();  
  58.         root.setLeft(root.getRight());  
  59.         root.setRight(treeTmp);  
  60.   
  61.         // 递归求解左右子树  
  62.         if (root.getLeft() != null) {  
  63.             mirrorRecursively(root.getLeft());  
  64.         }  
  65.   
  66.         if (root.getRight() != null) {  
  67.             mirrorRecursively(root.getRight());  
  68.         }  
  69.     }  
  70.       
  71.     /** 
  72.      * 递归方式实现前序遍历输出 
  73.      * @param root 
  74.      */  
  75.     public static void printPreOrder(BinaryTreeNode root) {  
  76.         if (root != null) {  
  77.             System.out.print(root.getValue() + "、");  
  78.             printPreOrder(root.getLeft());  
  79.             printPreOrder(root.getRight());  
  80.         }  
  81.     }  
  82. }  


面试题20:顺时针打印矩阵

面试题21:包含min函数的栈

题目大致为:
    定义栈的数据结构,在给类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用minpushpop的时间复杂度都是O(1)。
思路:
    可以建一个辅助的栈,在插入的过程中,插入栈1,同时在插入辅助栈的过程中要求与栈中的元素比较,若小于栈顶元素,则插入该元素,若大于栈顶元素,则继续插入栈顶元素。
Java实现:
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. import java.util.Stack;  
  4.   
  5. /** 
  6.  * 面试题21:包含min函数的栈 
  7.  *  
  8.  * @author dell 
  9.  *  
  10.  */  
  11. class StackWithMin {  
  12.     private Stack<Integer> stack;  
  13.     private Stack<Integer> stackHelp;// 一个辅助的栈  
  14.   
  15.     public StackWithMin() {  
  16.         stack = new Stack<Integer>();  
  17.         stackHelp = new Stack<Integer>();  
  18.     }  
  19.   
  20.     /** 
  21.      * 直接插入stack中,在插入stackHelp时,如果为空则直接插入,或者要判断与顶部元素的大小,若小于则插入,若大于则继续插入顶部元素 
  22.      *  
  23.      * @param t 
  24.      *            待插入元素 
  25.      */  
  26.     public void push(int t) {  
  27.         stack.push(t);  
  28.         // 插入辅助的栈  
  29.         if (stackHelp.size() == 0 || t < stackHelp.peek()) {  
  30.             stackHelp.push(t);  
  31.         } else {  
  32.             stackHelp.push(stackHelp.peek());  
  33.         }  
  34.     }  
  35.   
  36.     /** 
  37.      * 出栈,要求stack和stackHelp均不为空 
  38.      *  
  39.      * @return 
  40.      */  
  41.     public int pop() {  
  42.         assert (stack.size() > 0 && stackHelp.size() > 0);  
  43.   
  44.         stackHelp.pop();  
  45.         return stack.pop();  
  46.     }  
  47.   
  48.     /** 
  49.      * 取得最小值,最小值一定是stackHelp的栈顶元素 
  50.      *  
  51.      * @return 
  52.      */  
  53.     public int min() {  
  54.         assert (stack.size() > 0 && stackHelp.size() > 0);  
  55.   
  56.         return stackHelp.peek();  
  57.     }  
  58. }  
  59.   
  60. public class Item21 {  
  61.     public static void main(String args[]) {  
  62.         StackWithMin s = new StackWithMin();  
  63.         s.push(3);  
  64.         s.push(4);  
  65.         s.push(2);  
  66.         System.out.println(s.min());  
  67.         s.push(1);  
  68.         System.out.println(s.min());  
  69.     }  
  70.   
  71. }  


面试题22:栈的压入、弹出序列

题目大致为:
    输入两个整数序列,第一个序列表示栈的压入顺序,判断第二个序列是否为该栈的弹出顺序。
思路:
    主要分为这样的几种情况:首先判断两个序列的长度是否相等,若相等且大于0,则利用辅助栈模拟入栈和出栈。如果栈为空,则入栈,此时若栈顶元素与出栈序列的第一个元素相等,则出栈,否则继续入栈,最后判断栈是否为空且出栈序列所有的元素都遍历完。
Java代码:
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. import java.util.Stack;  
  4.   
  5. /** 
  6.  * 面试题22:栈的压入、弹出序列 
  7.  *  
  8.  * @author dell 
  9.  *  
  10.  */  
  11. public class Item22 {  
  12.     public static void main(String args[]) {  
  13.         // 测试用例  
  14.         // 第一组  
  15.         int pushArray_1[] = { 12345 };  
  16.         int popArray_1[] = { 45321 };  
  17.         System.out.println("第一组:" + isPopOrder(pushArray_1, popArray_1));  
  18.   
  19.         // 第二组  
  20.         int pushArray_2[] = { 12345 };  
  21.         int popArray_2[] = { 43512 };  
  22.         System.out.println("第二组:" + isPopOrder(pushArray_2, popArray_2));  
  23.   
  24.         // 第三组,主要长度不等  
  25.         int pushArray_3[] = { 12345 };  
  26.         int popArray_3[] = { 453 };  
  27.         System.out.println("第三组:" + isPopOrder(pushArray_3, popArray_3));  
  28.     }  
  29.   
  30.     /** 
  31.      * 判断序列popArray是否为pushArray的出栈序列 
  32.      *  
  33.      * @param pushArray 
  34.      *            入栈序列 
  35.      * @param popArray 
  36.      *            出栈序列 
  37.      * @return boolean 
  38.      */  
  39.     public static boolean isPopOrder(int pushArray[], int popArray[]) {  
  40.         boolean flag = false;  
  41.         // 能够执行的条件是这样的序列不为空,而且两个序列的长度是相等的  
  42.         if (pushArray.length > 0 && pushArray.length == popArray.length) {  
  43.             // 构造一个辅助栈,模拟入栈和出栈  
  44.             Stack<Integer> stack = new Stack<Integer>();  
  45.             int i = 0;  
  46.             int j = 0;  
  47.   
  48.             // 保证入栈序列全进入栈  
  49.             while (i < pushArray.length) {  
  50.                 // 当栈非空时,若栈顶元素与出栈序列中的元素相同,则出栈  
  51.                 if (stack.size() > 0 && stack.peek() == popArray[j]) {  
  52.                     stack.pop();  
  53.                     j++;  
  54.                 } else {// 若不相同或者栈为空,则在入栈序列中继续增加  
  55.                     stack.push(pushArray[i]);  
  56.                     i++;  
  57.                 }  
  58.             }  
  59.             // 此时栈中还有元素需要与出栈序列对比  
  60.             while (stack.size() > 0) {  
  61.                 // 若果相等就出栈  
  62.                 if (stack.peek() == popArray[j]) {  
  63.                     stack.pop();  
  64.                     j++;  
  65.                 } else {//若不相等就直接退出  
  66.                     break;  
  67.                 }  
  68.             }  
  69.             // 最终如果栈是空的,而且popArray中的所有数都遍历了,则是出栈序列  
  70.             if (stack.isEmpty() && j == popArray.length) {  
  71.                 flag = true;  
  72.             }  
  73.         }  
  74.         return flag;  
  75.     }  
  76.   
  77. }  

面试题23:从上往下打印二叉树

题目大致为:
    从上往下打印出儿茶树的每个结点,同一层的结点按照从左到右的顺序打印。
思路:
    可以使用队列的方式存储,先将根结点入队,若队列不为空,则取出队列的头,若这个结点有左孩子,则左孩子入队,若有右孩子,则右孩子入队。
二叉树的定义
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. public class BinaryTreeNode {  
  4.     private int value;  
  5.     private BinaryTreeNode left;  
  6.     private BinaryTreeNode right;  
  7.   
  8.     public BinaryTreeNode(int value) {  
  9.         this.value = value;  
  10.     }  
  11.   
  12.     public BinaryTreeNode(int value, BinaryTreeNode left, BinaryTreeNode right) {  
  13.         this.value = value;  
  14.         this.left = left;  
  15.         this.right = right;  
  16.     }  
  17.   
  18.     public int getValue() {  
  19.         return value;  
  20.     }  
  21.   
  22.     public void setValue(int value) {  
  23.         this.value = value;  
  24.     }  
  25.   
  26.     public BinaryTreeNode getLeft() {  
  27.         return left;  
  28.     }  
  29.   
  30.     public void setLeft(BinaryTreeNode left) {  
  31.         this.left = left;  
  32.     }  
  33.   
  34.     public BinaryTreeNode getRight() {  
  35.         return right;  
  36.     }  
  37.   
  38.     public void setRight(BinaryTreeNode right) {  
  39.         this.right = right;  
  40.     }  
  41.   
  42. }  

Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. import java.util.LinkedList;  
  4. import java.util.Queue;  
  5.   
  6. /** 
  7.  * 面试题23:从上往下打印二叉树 
  8.  *  
  9.  * @author dell 
  10.  *  
  11.  */  
  12. public class Item23 {  
  13.     public static void main(String args[]) {  
  14.         // 构建二叉树  
  15.         BinaryTreeNode root = new BinaryTreeNode(8);  
  16.         BinaryTreeNode t1 = new BinaryTreeNode(6);  
  17.         BinaryTreeNode t2 = new BinaryTreeNode(10);  
  18.         BinaryTreeNode t3 = new BinaryTreeNode(5);  
  19.         BinaryTreeNode t4 = new BinaryTreeNode(7);  
  20.         BinaryTreeNode t5 = new BinaryTreeNode(9);  
  21.         BinaryTreeNode t6 = new BinaryTreeNode(11);  
  22.         root.setLeft(t1);  
  23.         root.setRight(t2);  
  24.         t1.setLeft(t3);  
  25.         t1.setRight(t4);  
  26.         t2.setLeft(t5);  
  27.         t2.setRight(t6);  
  28.         t3.setLeft(null);  
  29.         t3.setRight(null);  
  30.         t4.setLeft(null);  
  31.         t4.setRight(null);  
  32.         t5.setLeft(null);  
  33.         t5.setRight(null);  
  34.         t6.setLeft(null);  
  35.         t6.setRight(null);  
  36.   
  37.         // 层次遍历  
  38.         System.out.println("层次遍历序列:");  
  39.         printFromTopToBottom(root);  
  40.   
  41.     }  
  42.   
  43.     /** 
  44.      * 层次遍历 
  45.      *  
  46.      * @param root根结点 
  47.      */  
  48.     public static void printFromTopToBottom(BinaryTreeNode root) {  
  49.         // 使用队列的形式  
  50.         Queue<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>();  
  51.         // 根结点入队  
  52.         queue.add(root);  
  53.   
  54.         // 队列非空  
  55.         while (!queue.isEmpty()) {  
  56.             // 去除队列的头  
  57.             BinaryTreeNode treeNode = queue.poll();  
  58.             System.out.print(treeNode.getValue() + "、");  
  59.   
  60.             // 左孩子不为空  
  61.             if (treeNode.getLeft() != null) {  
  62.                 queue.add(treeNode.getLeft());  
  63.             }  
  64.   
  65.             // 右孩子不为空  
  66.             if (treeNode.getRight() != null) {  
  67.                 queue.add(treeNode.getRight());  
  68.             }  
  69.         }  
  70.     }  
  71.   
  72. }  

面试题24:二查搜索树的后续遍历序列

题目大致为:
    输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则返回true,否则返回false。假设输入的数组的任意两个数字都互不相同。
思路:
    主要考察的是二叉搜索树和后序遍历的性质,其中后序遍历的最后一个数是根结点,在二叉搜索树中,左子树的值都小于根结点,右子树的值都大于跟结点,这样便能构造左右子树的序列,用同样的方法分别处理左右子树序列,这便是一个递归的问题。
树的结构
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. public class BinaryTreeNode {  
  4.     private int value;  
  5.     private BinaryTreeNode left;  
  6.     private BinaryTreeNode right;  
  7.   
  8.     public BinaryTreeNode(int value) {  
  9.         this.value = value;  
  10.     }  
  11.   
  12.     public BinaryTreeNode(int value, BinaryTreeNode left, BinaryTreeNode right) {  
  13.         this.value = value;  
  14.         this.left = left;  
  15.         this.right = right;  
  16.     }  
  17.   
  18.     public int getValue() {  
  19.         return value;  
  20.     }  
  21.   
  22.     public void setValue(int value) {  
  23.         this.value = value;  
  24.     }  
  25.   
  26.     public BinaryTreeNode getLeft() {  
  27.         return left;  
  28.     }  
  29.   
  30.     public void setLeft(BinaryTreeNode left) {  
  31.         this.left = left;  
  32.     }  
  33.   
  34.     public BinaryTreeNode getRight() {  
  35.         return right;  
  36.     }  
  37.   
  38.     public void setRight(BinaryTreeNode right) {  
  39.         this.right = right;  
  40.     }  
  41.   
  42. }  

Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. import java.util.Arrays;  
  4.   
  5. /** 
  6.  * 面试题24:二叉搜索树的后序遍历序列 
  7.  *  
  8.  * @author dell 
  9.  *  
  10.  */  
  11. public class Item24 {  
  12.     public static void main(String args[]) {  
  13.         int array[] = { 576911108 };  
  14.         System.out.println(verifySquenceOfBST(array));  
  15.     }  
  16.   
  17.     public static boolean verifySquenceOfBST(int squence[]) {  
  18.         // 判断序列是否满足要求  
  19.         int length = squence.length;  
  20.         if (squence == null || length <= 0) {  
  21.             return false;  
  22.         }  
  23.         // 序列的最后一个数是二查搜索树的根结点  
  24.         int root = squence[length - 1];  
  25.         int i;  
  26.         for (i = 0; i < length; i++) {  
  27.             // 当只有根结点的时候要用等于去判断  
  28.             if (squence[i] >= root) {  
  29.                 break;  
  30.             }  
  31.         }  
  32.   
  33.         // 判断右子树是否满足要求  
  34.         for (int j = i; j < length - 1; j++) {  
  35.             if (squence[j] < root) {  
  36.                 return false;  
  37.             }  
  38.         }  
  39.   
  40.         // 左子树结点的个数  
  41.         int leftNum = i;  
  42.         // 构造左子树的序列  
  43.         int left[] = Arrays.copyOfRange(squence, 0, leftNum);  
  44.         // 构造右子树的序列  
  45.         int right[] = Arrays.copyOfRange(squence, leftNum, length - 1);  
  46.         boolean leftBool = true;  
  47.         boolean rightBool = true;  
  48.         // 当左子树的序列存在时  
  49.         if (left.length > 0) {  
  50.             leftBool = verifySquenceOfBST(left);  
  51.         }  
  52.         // 当右子树的序列存在时  
  53.         if (right.length > 0) {  
  54.             rightBool = verifySquenceOfBST(right);  
  55.         }  
  56.         return (leftBool && rightBool);  
  57.   
  58.     }  
  59. }  

面试题25:二叉树中和为某一值的路径
面试题26:复杂链表的复制
面试题27:二查搜索树与双向链表
面试题28:字符串的排列

面试题29:数组中出现次数超过一半的数字

题目大致为:
    数组中有一个数字出现的次数超过数组长度的一般,找出这个数字。
思路:
    在遍历数组的过程中纪录两个量,一个是数组中的数字,一个是次数,当下一个数字和我们保存的一致时则次数加1,当不一致时次数减1,当次数为0时,重置两个量。数组中的数字为当前访问的值,次数为1。这里主要是利用了出现的次数超过了一半,其实就是超过一半数出现的次数减去其他的数出现的次数始终是大于0的。
Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题29:数组中出现次数超过一半的数字 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item29 {  
  10.     public static void main(String args[]) {  
  11.         int testArray[] = { 123222542 };  
  12.         System.out.println("超过一半的数字为:" + moreThanHalfNum(testArray));  
  13.     }  
  14.   
  15.     public static int moreThanHalfNum(int array[]) {  
  16.         // 一种巧妙的解法  
  17.         int length = array.length;// 数组的长度  
  18.         int result = array[0];  
  19.         int times = 0;  
  20.         for (int i = 1; i < length; i++) {  
  21.             if (times == 0) {  
  22.                 result = array[i];  
  23.                 times = 1;  
  24.             } else if (array[i] == result) {  
  25.                 times++;  
  26.             } else {  
  27.                 times--;  
  28.             }  
  29.         }  
  30.         return result;  
  31.     }  
  32. }  

面试题30:最小的k个数

题目大致为:
    输入n个整数,找出其中最小的k个数。
思路:
    使用类似二叉查找树的形式实现,控制好树中的结点个数为k
Java代码
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. import java.util.Iterator;  
  4. import java.util.TreeSet;  
  5.   
  6. /** 
  7.  * 面试题30:最小的k个数 
  8.  *  
  9.  * @author dell 
  10.  *  
  11.  */  
  12. public class Item30 {  
  13.     public static void main(String args[]) {  
  14.         // 测试的例子  
  15.         int array[] = { 45162738 };  
  16.         final int k = 4;  
  17.         TreeSet<Integer> set = getLeastNumbers(array, k);  
  18.         // 输出  
  19.         Iterator<Integer> it = set.iterator();  
  20.         System.out.println("最小的" + k + "个数为:");  
  21.         while (it.hasNext()) {  
  22.             System.out.print(it.next() + "、");  
  23.         }  
  24.   
  25.     }  
  26.   
  27.     public static TreeSet<Integer> getLeastNumbers(int array[], int k) {  
  28.         TreeSet<Integer> set = new TreeSet<Integer>();  
  29.         // 判断k和array的合法性  
  30.         if (array == null || k <= 0) {  
  31.             return null;  
  32.         }  
  33.   
  34.         for (int i = 0; i < array.length; i++) {  
  35.             if (set.size() < k) {// 如果TreeSet中的元素小于K个,则直接插入  
  36.                 set.add(array[i]);  
  37.             } else {// TreeSet中的元素大于K个  
  38.                 if (set.last() > array[i]) {// 最大的元素大于array[i]  
  39.                     set.pollLast();// 移除  
  40.                     set.add(array[i]);// 加入新的  
  41.                 }  
  42.             }  
  43.         }  
  44.   
  45.         return set;  
  46.   
  47.     }  
  48.   
  49. }  

面试题31:连续字数组的最大和

题目大致为:
    输入一个整型数组,数组里有正数也有负数。数组中一个或者连续的多个整数组成一个字数组。求所有字数组的和的最大值。要求时间复杂度为O(n)
思路:
    因为时间复杂度为O(n),则只能遍历一次数组,这里同时使用两个变量currentSum和finalGreatSum,其中currentSum保存的是当前的和,若currentSum<0,则从下一个位置从新记录,finalGreatSum记录的是历史的最小值,只有当currentSum>finalGreatSum时用currentSum替换finalGreatSum。
Java代码
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题31:连续字数组的最大和 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item31 {  
  10.     public static void main(String args[]) {  
  11.         // 测试  
  12.         int array[] = { 1, -2310, -472, -5 };  
  13.         int result = findGreatSumOfSubArray(array);  
  14.         System.out.println("子数组的最大和为:" + result);  
  15.     }  
  16.   
  17.     public static int findGreatSumOfSubArray(int array[]) {  
  18.         // 用currentSum记录当前的和  
  19.         int currentSum = 0;  
  20.         // 用finalGreatSum记录历史最佳  
  21.         int finalGreatSum = 0;  
  22.   
  23.         for (int i = 0; i < array.length; i++) {  
  24.             currentSum += array[i];  
  25.             // 如果currentSum>0则记录  
  26.             if (currentSum > 0) {  
  27.                 // 如果currentSum>finalGreatSum则替换finalGreatSum  
  28.                 if (currentSum > finalGreatSum) {  
  29.                     finalGreatSum = currentSum;  
  30.                 }  
  31.             } else {  
  32.                 currentSum = 0;  
  33.             }  
  34.         }  
  35.         return finalGreatSum;  
  36.     }  
  37.   
  38. }  

面试题32:从1到n整数中1出现的次数
面试题33:把数组排成最小的数

面试题34:丑数

题目大致为:
    丑数的定义为:只包含因子2,3和5的数。求按从小到大的顺序的第1500个丑数。约定:1当做第一个丑数。
思路:
    设置三个指针分别代表该位置*2,*3和*5,并将这三个数中的最小值插入数组中,若当前位置的值*对应的因子<=刚插入的值,便将该指针后移,直到新的位置上的值*对应的因子>刚插入的值。
Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题34:丑数 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item34 {  
  10.     public static void main(String args[]) {  
  11.         int index = 7;  
  12.         System.out.println("第" + index + "个丑数为:" + getUglyNum(7));  
  13.     }  
  14.   
  15.     /** 
  16.      * 根据index计算丑数 
  17.      *  
  18.      * @param index丑数的下标 
  19.      * @return丑数 
  20.      */  
  21.     public static int getUglyNum(int index) {  
  22.         // 检查index  
  23.         if (index <= 0) {  
  24.             return 0;  
  25.         }  
  26.         // 为了便于存储,可以建立数组保存中间结果  
  27.         int tmp[] = new int[index];  
  28.         // 保存第一个  
  29.         tmp[0] = 1;  
  30.         // 记录三组数的位置  
  31.         int multi2 = 0;  
  32.         int multi3 = 0;  
  33.         int multi5 = 0;  
  34.   
  35.         int nextUglyNum = 1;  
  36.         while (nextUglyNum < index) {  
  37.             int min = findMin(tmp[multi2] * 2, tmp[multi3] * 3, tmp[multi5] * 5);  
  38.             tmp[nextUglyNum] = min;  
  39.   
  40.             // 重新计算multi2,multi3,multi5  
  41.             while (tmp[multi2] * 2 <= min) {  
  42.                 multi2++;  
  43.             }  
  44.             while (tmp[multi3] * 3 <= min) {  
  45.                 multi3++;  
  46.             }  
  47.             while (tmp[multi5] * 5 <= min) {  
  48.                 multi5++;  
  49.             }  
  50.             nextUglyNum++;  
  51.         }  
  52.         return tmp[index - 1];  
  53.     }  
  54.   
  55.     /** 
  56.      * 计算三个数的最小值 
  57.      *  
  58.      * @param a 
  59.      * @param b 
  60.      * @param c 
  61.      * @return 
  62.      */  
  63.     public static int findMin(int a, int b, int c) {  
  64.         int minTmp = (a < b ? a : b);  
  65.         return (minTmp < c ? minTmp : c);  
  66.     }  
  67. }  

面试题35:第一个只出现一次的字符

题目大致为:
    在字符串中找出第一个只出现一次的字符。
思路:
    在Java中可以把字符串转换成字符数组处理,可以使用HashMap的数据结构存储,其中key为字符,value为对应出现的次数,这样通过两次遍历字符数组就可以找出,其中,第一次是构建HashMap,第二次是对每个字符判断其HashMap中对应的value的值是否为1。
Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. import java.util.HashMap;  
  4.   
  5. /** 
  6.  * 面试题35:第一个只出现一次的字符 
  7.  *  
  8.  * @author dell 
  9.  *  
  10.  */  
  11. public class Item35 {  
  12.     public static void main(String args[]) {  
  13.         // 测试  
  14.         String s = "abaccdeff";  
  15.         char c[] = s.toCharArray();  
  16.         System.out.println("第一个只出现一次的字符为:" + first(c));  
  17.     }  
  18.   
  19.     /** 
  20.      * 查找第一次只出现一次的字符 
  21.      *  
  22.      * @param c待查找的字符数组 
  23.      * @return 
  24.      */  
  25.     public static char first(char c[]) {  
  26.         char tmp = 0;  
  27.         // 可以使用Hash表,key存储的是字符,value存储的是出现的次数  
  28.         HashMap<Character, Integer> map = new HashMap<Character, Integer>();  
  29.         for (int i = 0; i < c.length; i++) {  
  30.             // hash表中已经存在key  
  31.             if (map.containsKey(c[i])) {  
  32.                 // 修改其value  
  33.                 int value = map.get(c[i]);// 根据key得到value  
  34.                 map.remove(c[i]);  
  35.                 map.put(c[i], value + 1);  
  36.             } else {  
  37.                 map.put(c[i], 1);  
  38.             }  
  39.         }  
  40.         // 插入完毕后依次搜索  
  41.         for (int i = 0; i < c.length; i++) {  
  42.             if (map.get(c[i]) == 1) {  
  43.                 tmp = c[i];  
  44.                 break;// 退出循环  
  45.             }  
  46.         }  
  47.         return tmp;  
  48.     }  
  49. }  

面试题36:数组中的逆序对

面试题37:两个链表的第一个公共结点

题目大致为:
    输入两个链表,找出它们的第一个公共结点。
思路:

    第一个公共结点开始往后都是公共结点,所以在末尾向前遍历,就可以找到第一个公共结点。利用上面的思想,可以先计算两个链表的长度,计算两个链表的长度差,然后先遍历较长的链表,等到剩余长度相等时开始同时遍历,这样就能较快地找到相同的结点,时间复杂度为O(m+n),其中mn分别为两个链表的长度。
Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题37:两个链表的第一个公共结点 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item37 {  
  10.     public static void main(String args[]) {  
  11.         // 构建链表  
  12.         ListNode head1 = new ListNode(1);  
  13.         ListNode node_2 = new ListNode(2);  
  14.         ListNode node_3 = new ListNode(3);  
  15.         ListNode head2 = new ListNode(4);  
  16.         ListNode node_5 = new ListNode(5);  
  17.         ListNode node_6 = new ListNode(6);  
  18.         ListNode node_7 = new ListNode(7);  
  19.         head1.setNext(node_2);  
  20.         node_2.setNext(node_3);  
  21.         node_3.setNext(node_6);  
  22.         node_6.setNext(node_7);  
  23.         node_7.setNext(null);  
  24.         head2.setNext(node_5);  
  25.         node_5.setNext(node_6);  
  26.   
  27.         ListNode result = findFirst(head1, head2);  
  28.         System.out.println("第一个公共结点:" + result.getValue());  
  29.     }  
  30.       
  31.     /** 
  32.      * 查找第一个公共结点 
  33.      * @param head1链表1的头指针 
  34.      * @param head2链表2的头指针 
  35.      * @return 
  36.      */  
  37.     public static ListNode findFirst(ListNode head1, ListNode head2) {  
  38.         ListNode p1 = head1;  
  39.         ListNode p2 = head2;  
  40.         int list_1_len = 0;  
  41.         int list_2_len = 0;  
  42.         // 分别计算两个链表的长度  
  43.         while (p1 != null) {  
  44.             list_1_len++;  
  45.             p1 = p1.getNext();  
  46.         }  
  47.   
  48.         while (p2 != null) {  
  49.             list_2_len++;  
  50.             p2 = p2.getNext();  
  51.         }  
  52.   
  53.         // 长度差  
  54.         int nLength = list_1_len - list_2_len;  
  55.   
  56.         ListNode pLong = head1;  
  57.         ListNode pShort = head2;  
  58.         if (list_1_len < list_2_len) {  
  59.             pLong = head2;  
  60.             pShort = head1;  
  61.             nLength = list_2_len - list_1_len;  
  62.         }  
  63.   
  64.         // 长的先走nLength步  
  65.         for (int i = 0; i < nLength; i++) {  
  66.             pLong = pLong.getNext();  
  67.         }  
  68.   
  69.         // 此时长度相等,一起向前走,并判断他们的值是否相等  
  70.         while (pLong != null && pShort != null && pLong != pShort) {  
  71.             pLong = pLong.getNext();  
  72.             pShort = pShort.getNext();  
  73.         }  
  74.   
  75.         return pLong;  
  76.   
  77.     }  
  78.   
  79. }  

面试题38:数字在排序数组中出现的次数

题目大致为:
    统计一个数字在排序数组中出现的次数。
思路:
    由于是排序数组,要查找其中的一个数字,最简便的方法便是折半查找,这样我们可以先查找最先出现的位置和最后出现的位置,数出中间的个数便为总共的出现次数。
Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题38:数字在排序数组中出现的次数 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item38 {  
  10.     public static void main(String args[]) {  
  11.         // 测试  
  12.         int array[] = { 12333345 };  
  13.         int k = 3;// 待查找的数  
  14.         System.out.println(k + "的个数为:" + getNumOfK(array, k));  
  15.     }  
  16.   
  17.     /** 
  18.      * 通过计算初始位置和结束位置,计算出所有的个数 
  19.      *  
  20.      * @param array 
  21.      * @param k 
  22.      * @return 
  23.      */  
  24.     public static int getNumOfK(int array[], int k) {  
  25.         int num = 0;  
  26.         if (array != null) {  
  27.             int index_start = getFirstK(array, k, 0, array.length - 1);// 初始位置  
  28.             int index_end = getLastK(array, k, 0, array.length - 1);// 结束位置  
  29.   
  30.             if (index_start > -1 && index_end > -1) {  
  31.                 num = index_end - index_start + 1;  
  32.             }  
  33.         }  
  34.         return num;  
  35.     }  
  36.   
  37.     /** 
  38.      * 查找k在数组中的最先出现的位置 
  39.      *  
  40.      * @param array初始数组 
  41.      * @param k待查找的值 
  42.      * @return 
  43.      */  
  44.     public static int getFirstK(int array[], int k, int low, int high) {  
  45.         // 判断low和high  
  46.         if (low > high) {  
  47.             return -1;  
  48.         }  
  49.         // 折半查找的思想,找中间位置  
  50.         int middle = (low + high) / 2;  
  51.   
  52.         // 查找是否为k  
  53.         if (array[middle] == k) {// 查找的值是为k,剩下的是判断是否是第一个k  
  54.             // 是第一个  
  55.             if ((middle > 0 && array[middle - 1] != k) || middle == 0) {  
  56.                 return middle;  
  57.             }  
  58.             // 不是第一个  
  59.             else {  
  60.                 high = middle - 1;  
  61.             }  
  62.         } else if (array[middle] > k) {// 在左侧  
  63.             high = middle - 1;  
  64.         } else {// 在右侧  
  65.             low = middle + 1;  
  66.         }  
  67.   
  68.         return getFirstK(array, k, low, high);  
  69.     }  
  70.   
  71.     /** 
  72.      * 类似getFirstK,查找最后一个为K 
  73.      *  
  74.      * @param array 
  75.      * @param k 
  76.      * @return 
  77.      */  
  78.     public static int getLastK(int array[], int k, int low, int high) {  
  79.         // 判断low和high  
  80.         if (low > high) {  
  81.             return -1;  
  82.         }  
  83.         int middle = (low + high) / 2;  
  84.   
  85.         // 查找是否为k  
  86.         if (array[middle] == k) {// 查找的值是为k,剩下的是判断是否是最后一个k  
  87.             // 是最后一个  
  88.             if ((middle > 0 && array[middle + 1] != k)  
  89.                     || middle == array.length - 1) {  
  90.                 return middle;  
  91.             }  
  92.             // 不是最后一个  
  93.             else {  
  94.                 low = middle + 1;  
  95.             }  
  96.         } else if (array[middle] > k) {// 在左侧  
  97.             high = middle - 1;  
  98.         } else {// 在右侧  
  99.             low = middle + 1;  
  100.         }  
  101.   
  102.         return getLastK(array, k, low, high);  
  103.     }  
  104.   
  105. }  

面试题39:二叉树的深度

题目大致为:
    输入一棵二叉树的根结点,求该树的深度。其中,从根结点到叶结点一次经过的结点形成树的一条路径,最长路径的长度为树的深度。
思路:
    树的遍历可以利用递归实现,查找深度其实也是遍历的一种,分别遍历左右子树,找到左右子树中结点的个数。
树的结构
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. public class BinaryTreeNode {  
  4.     private int value;  
  5.     private BinaryTreeNode left;  
  6.     private BinaryTreeNode right;  
  7.   
  8.     public BinaryTreeNode(int value) {  
  9.         this.value = value;  
  10.     }  
  11.   
  12.     public BinaryTreeNode(int value, BinaryTreeNode left, BinaryTreeNode right) {  
  13.         this.value = value;  
  14.         this.left = left;  
  15.         this.right = right;  
  16.     }  
  17.   
  18.     public int getValue() {  
  19.         return value;  
  20.     }  
  21.   
  22.     public void setValue(int value) {  
  23.         this.value = value;  
  24.     }  
  25.   
  26.     public BinaryTreeNode getLeft() {  
  27.         return left;  
  28.     }  
  29.   
  30.     public void setLeft(BinaryTreeNode left) {  
  31.         this.left = left;  
  32.     }  
  33.   
  34.     public BinaryTreeNode getRight() {  
  35.         return right;  
  36.     }  
  37.   
  38.     public void setRight(BinaryTreeNode right) {  
  39.         this.right = right;  
  40.     }  
  41.   
  42. }  

Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题39:二叉树的深度 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item39 {  
  10.   
  11.     public static void main(String args[]) {  
  12.         BinaryTreeNode root = new BinaryTreeNode(1);  
  13.         BinaryTreeNode node_2 = new BinaryTreeNode(2);  
  14.         BinaryTreeNode node_3 = new BinaryTreeNode(3);  
  15.         BinaryTreeNode node_4 = new BinaryTreeNode(4);  
  16.         BinaryTreeNode node_5 = new BinaryTreeNode(5);  
  17.         BinaryTreeNode node_6 = new BinaryTreeNode(6);  
  18.         BinaryTreeNode node_7 = new BinaryTreeNode(7);  
  19.         root.setLeft(node_2);  
  20.         root.setRight(node_3);  
  21.         node_2.setLeft(node_4);  
  22.         node_2.setRight(node_5);  
  23.         node_3.setLeft(null);  
  24.         node_3.setRight(node_6);  
  25.         node_4.setLeft(null);  
  26.         node_4.setRight(null);  
  27.         node_5.setLeft(node_7);  
  28.         node_5.setRight(null);  
  29.         node_6.setLeft(null);  
  30.         node_6.setRight(null);  
  31.         node_7.setLeft(null);  
  32.         node_7.setRight(null);  
  33.   
  34.         // 计算深度  
  35.         System.out.println("二叉树的深度为:" + treeDepth(root));  
  36.     }  
  37.   
  38.     /** 
  39.      * 计算二叉树的深度 
  40.      *  
  41.      * @param root根结点 
  42.      * @return深度 
  43.      */  
  44.     public static int treeDepth(BinaryTreeNode root) {  
  45.         // 先判断树是否存在  
  46.         if (root == null) {  
  47.             return 0;  
  48.         }  
  49.   
  50.         // 递归实现左右子树的深度  
  51.         int leftDepth = treeDepth(root.getLeft());  
  52.         int rightDepth = treeDepth(root.getRight());  
  53.   
  54.         // 找到最大值  
  55.         return (leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1));  
  56.     }  
  57.   
  58. }  

补充:判断一棵树是否为平衡二叉树
题目大致为:
输入一棵二叉树的根结点,判断该树是不是平衡二叉树。其中,如果某二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
面试题40:数组中只出现一次的数字

面试题41:和为s的两个数字VS和为s的连续正数序列

题目一大致为:
    输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得他们的和正好是s。
思路:
    对于有序数组,用两个指针分别指向头和尾部,然后将他们的和与s比较,若等于s,退出;若<s,则头指针向后移;若>s,则尾指针向前移;直到两个指针相遇。
Java代码
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题41:和为s的两个数字VS和为s的连续正数序列 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item41 {  
  10.     public static void main(String args[]) {  
  11.         int array[] = { 12471115 };  
  12.         int s = 15;  
  13.         int result[] = new int[2];// 存储两个解  
  14.         boolean flag = findNumWithSum(array, result, s);  
  15.   
  16.         if (flag == true) {// 存在这样的解,输出  
  17.             System.out.println("一组解为:" + result[0] + "、" + result[1]);  
  18.         } else {  
  19.             System.out.println("不存在");  
  20.         }  
  21.   
  22.     }  
  23.   
  24.     /** 
  25.      * 和为s的两个数组 
  26.      *  
  27.      * @param array原始数组 
  28.      * @param result结果数组 
  29.      * @param s和 
  30.      * @return 
  31.      */  
  32.     public static boolean findNumWithSum(int array[], int result[], int s) {  
  33.         int length = array.length;  
  34.         boolean flag = false;  
  35.         // 条件检查,要保证能存储两个数  
  36.         if (length <= 0 || result.length != 2) {  
  37.             return flag;  
  38.         }  
  39.   
  40.         // 两个指针  
  41.         int low = 0;  
  42.         int high = length - 1;  
  43.   
  44.         while (low < high) {  
  45.             // 如果相等  
  46.             if (array[low] + array[high] == s) {  
  47.                 // 记录下  
  48.                 result[0] = array[low];  
  49.                 result[1] = array[high];  
  50.                 flag = true;// 表示找到了  
  51.                 break;  
  52.             }  
  53.             // 如果>  
  54.             else if (array[low] + array[high] > s) {  
  55.                 high--;// 减小  
  56.             }  
  57.             // 如果小于  
  58.             else {  
  59.                 low++;// 增加  
  60.             }  
  61.         }  
  62.         return flag;  
  63.     }  
  64.   
  65. }  

题目二大致为:
    输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)。
思路:
   s至少要为3,这样才能满足至少含有两个数,若s>3,这时可以查找lowhigh之间的和,若=s,则输出;若<s,则增加high,若>s,则增加low,这样就减少了他们之间的数,直到low<(1+s)/2;即小于中间值,因为两个中间值的和可能为s
Java代码
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 题目二:和为s的连续序列 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item41_1 {  
  10.   
  11.     public static void main(String args[]) {  
  12.         System.out.println("打印序列:");  
  13.         findSquenceWithSum(15);  
  14.   
  15.     }  
  16.   
  17.     /** 
  18.      * 查找序列 
  19.      *  
  20.      * @param s和 
  21.      */  
  22.     public static void findSquenceWithSum(int s) {  
  23.         if (s < 3) {  
  24.             System.out.println("不存在");  
  25.             return;  
  26.         }  
  27.         int high = 2;// 至少有两个,那么最小也得为3  
  28.         int low = 1;  
  29.         int currentSum = low + high;// 记录当前的和  
  30.   
  31.         int end = (1 + s) / 2;  
  32.         while (low < end) {  
  33.             // 若==s,则返回  
  34.             if (currentSum == s) {  
  35.                 printSquence(low, high);  
  36.             }  
  37.             // 大于,要减小  
  38.             while (currentSum > s && low < end) {  
  39.                 currentSum -= low;  
  40.                 low++;  
  41.                 if (currentSum == s) {  
  42.                     printSquence(low, high);  
  43.                 }  
  44.             }  
  45.             high++;  
  46.             currentSum += high;  
  47.   
  48.         }  
  49.     }  
  50.   
  51.     /** 
  52.      * 打印函数 
  53.      *  
  54.      * @param low下界 
  55.      * @param high上界 
  56.      */  
  57.     public static void printSquence(int low, int high) {  
  58.         // 判断是否符合要求  
  59.         if (high - low <= 0) {// 只有一个数或者high<low  
  60.             System.out.println("不存在");  
  61.             return;  
  62.         }  
  63.         for (int i = low; i <= high; i++) {  
  64.             System.out.print(i + "、");  
  65.         }  
  66.         System.out.println();// 换行  
  67.     }  
  68. }  

面试题42:翻转单词顺序VS左旋转字符串

题目一大致为:
    输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。
思路:
    两次翻转,对于字符串"I am a student.",首先进行第一次翻转,即翻转完为:".tneduts a ma I",然后再对每个单词翻转,最终为:"student. a am I"
Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题42:翻转单词顺序VS左旋转字符串 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item42 {  
  10.     public static void main(String args[]) {  
  11.         String s = "I am a student.";  
  12.   
  13.         System.out.println(reverseSentence(s));  
  14.     }  
  15.   
  16.     /** 
  17.      * 翻转整个字符串 
  18.      *  
  19.      * @param s 
  20.      * @return 
  21.      */  
  22.     public static String reverseSentence(String s) {  
  23.         // 将字符串转换成字符数组  
  24.         char c[] = s.toCharArray();  
  25.         // 先将整个字符数组翻转  
  26.         reverse(c, 0, c.length - 1);  
  27.   
  28.         // 再翻转每一个单词  
  29.         int lengthOfTerm = 0;// 单词的长度  
  30.         for (int i = 0; i < c.length; i++) {  
  31.             if (c[i] == ' ') {  
  32.                 int end = i - 1;// 末尾的位置  
  33.                 int start = end - lengthOfTerm + 1;  
  34.                 reverse(c, start, end);// 翻转单词  
  35.                 lengthOfTerm = 0;// 重新置0,做下一次的统计  
  36.             } else {  
  37.                 lengthOfTerm++;// 增加单词的个数  
  38.             }  
  39.         }  
  40.   
  41.         return new String(c);  
  42.     }  
  43.   
  44.     /** 
  45.      * 通用的对每个字符数组翻转 
  46.      *  
  47.      * @param c 
  48.      * @param start字符数组的开始 
  49.      * @param end字符数组的结束 
  50.      */  
  51.     public static void reverse(char c[], int start, int end) {  
  52.         // 不满足要求的输入  
  53.         if (c == null || start > end) {  
  54.             return;  
  55.         }  
  56.         // 只有一个字符  
  57.         if (start == end) {  
  58.             return;  
  59.         }  
  60.   
  61.         while (start < end) {  
  62.             char tmp = c[start];  
  63.             c[start] = c[end];  
  64.             c[end] = tmp;  
  65.             start++;  
  66.             end--;  
  67.         }  
  68.     }  
  69.   
  70. }  

题目二大致为:
    字符串的左旋转操作时把字符串前面的若干个字符转移到字符串的尾部。如输入字符串为"abcdefg"和数字2,则返回"cdefgab"
思路:
    类似上面的两次翻转。
Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 题目二:左旋转字符串 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item42_1 {  
  10.     public static void main(String args[]) {  
  11.         String s = "abcdefg";  
  12.         int k = 2;  
  13.         System.out.println(leftRotateString(s, k));  
  14.     }  
  15.   
  16.     /** 
  17.      * 左旋转 
  18.      *  
  19.      * @param s原始字符串 
  20.      * @param k旋转的个数 
  21.      * @return 
  22.      */  
  23.     public static String leftRotateString(String s, int k) {  
  24.         // 先检查s和k的合法性  
  25.         if (s == null || k <= 0) {  
  26.             return s;  
  27.         }  
  28.   
  29.         // 将字符串转换成字符数组  
  30.         char c[] = s.toCharArray();  
  31.         // 翻转整个字符串  
  32.         reverse(c, 0, c.length - 1);  
  33.   
  34.         // 找到k的位置  
  35.         reverse(c, 0, c.length - 1 - k);  
  36.         reverse(c, c.length - k, c.length - 1);  
  37.         return new String(c);  
  38.     }  
  39.   
  40.     /** 
  41.      * 通用的对每个字符数组翻转 
  42.      *  
  43.      * @param c 
  44.      * @param start字符数组的开始 
  45.      * @param end字符数组的结束 
  46.      */  
  47.     public static void reverse(char c[], int start, int end) {  
  48.         // 不满足要求的输入  
  49.         if (c == null || start > end) {  
  50.             return;  
  51.         }  
  52.         // 只有一个字符  
  53.         if (start == end) {  
  54.             return;  
  55.         }  
  56.   
  57.         while (start < end) {  
  58.             char tmp = c[start];  
  59.             c[start] = c[end];  
  60.             c[end] = tmp;  
  61.             start++;  
  62.             end--;  
  63.         }  
  64.     }  
  65.   
  66. }  

面试题43:n个骰子的点数

面试题44:扑克牌的顺序

题目大致为:
    从扑克牌中随机抽出5张牌,判断是不是一个顺子,即这5张牌是不是连续的。2~10为数字本身,A为1,J为11,Q为12,K为13,而大、小王可以看成是任意数字。
思路:
    实则本题是判断一个数组是否是连续的,将大、小王看成是0,0可以充当任何的数。这样我的思路是:先对数组排序,排序后统计出0的个数,在计算非0数之间的缺少的数字个数的总和,若是在这个过程中发现前后两个的差为0则为相同的元素,则不符合题意;在满足题意的情况下,若是0的个数大于等于缺少的数字个数的总和,那么满足条件,否则不满足条件。
Java代码:
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. import java.util.Arrays;  
  4.   
  5. /** 
  6.  * 面试题44:扑克牌的顺序 
  7.  *  
  8.  * @author dell 
  9.  *  
  10.  */  
  11. public class Item44 {  
  12.     public static void main(String args[]) {  
  13.         // 模拟随机抽牌,大小王为0,A为1,J为11,Q为12,K为13,其实就是个数组,判断数组是否是顺序的  
  14.   
  15.         // 测试1:正好填补  
  16.         int array_1[] = { 00145 };  
  17.         System.out.println(isContinuous(array_1));  
  18.         // 测试2:不能填补  
  19.         int array_2[] = { 01456 };  
  20.         System.out.println(isContinuous(array_2));  
  21.         // 测试3:有相同元素  
  22.         int array_3[] = { 01334, };  
  23.         System.out.println(isContinuous(array_3));  
  24.     }  
  25.   
  26.     public static boolean isContinuous(int array[]) {  
  27.         // 由于数组的规模很小,则可以直接使用库函数完成  
  28.         // 作者有句话很重要:通常我们认为不同级别的时间复杂度只有当n足够大的时候才有意义  
  29.         Arrays.sort(array);  
  30.   
  31.         int numOfZero = 0;// 统计0的个数  
  32.         int sumOfError = 0;  
  33.         for (int i = 0; i < array.length - 1; i++) {  
  34.             if (array[i] == 0) {  
  35.                 numOfZero++;  
  36.             } else {// 非零的情况  
  37.                     // 若有相同的元素  
  38.                 if (array[i + 1] - array[i] == 0) {  
  39.                     return false;  
  40.                 } else {  
  41.                     sumOfError += (array[i + 1] - array[i] - 1);  
  42.                 }  
  43.             }  
  44.         }  
  45.         if (numOfZero >= sumOfError) {// 0能填补空缺  
  46.             return true;  
  47.         } else {  
  48.             return false;  
  49.         }  
  50.     }  
  51.   
  52. }  

面试题45:圆圈中最后剩下的数字

题目大致为:
    0,1,...,n-1n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字。求出这个圆圈里剩下的最后一个数字。
思路:
    第一种办法就是通过环形链表模拟这样的删除过程;但是作者推导出了这样的关系式,具体关系式可以见书P231
Java代码
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题45:圆圈中最后剩下的数字 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item45 {  
  10.     public static void main(String args[]) {  
  11.         System.out.println(lastRemaining(53));  
  12.     }  
  13.   
  14.     /** 
  15.      * 比较巧妙的办法是推导出一个推导公式 
  16.      *  
  17.      * @param n 
  18.      *            :n个数字 
  19.      * @param m 
  20.      *            :删除第m个数字 
  21.      * @return 
  22.      */  
  23.     public static int lastRemaining(int n, int m) {  
  24.         if (n < 1 || m < 1) {  
  25.             return -1;  
  26.         }  
  27.   
  28.         int last = 0;  
  29.         for (int i = 2; i <= n; i++) {  
  30.             last = (last + m) % i;  
  31.         }  
  32.         return last;  
  33.     }  
  34.   
  35. }  

面试题46:求1+2+...+n

题目大致为:
    求1+2+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路:
    本题书上用C++实现,其中解法一:利用构造函数求解。但是在Java中声明对象数组必须对数组中的对象初始化才能开辟空间。所以我这题不知道利用Java怎么实现。书中的其他几种方式主要是利用C++的一些特性。如果有人知道,可以告诉我,谢谢。

面试题47:不用加减乘除做加法

题目大致为:
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
思路:
使用位运算。分三步:第一、不考虑进位,用异或模拟加法;第二、用与运算并左移一位模拟进位;第三、重复前面两步。
Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题47:不用加减乘除做加法 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item47 {  
  10.   
  11.     public static void main(String args[]) {  
  12.         int a = 1;  
  13.         int b = 2;  
  14.         System.out.println(add(a, b));  
  15.     }  
  16.   
  17.     public static int add(int num1, int num2) {  
  18.         int sum = 0;  
  19.         int carry = 0;  
  20.         do {  
  21.             sum = num1 ^ num2;// 第一步,异或  
  22.             carry = (num1 & num2) << 1;// 第二步,进位  
  23.             // 第三步,相加  
  24.             num1 = sum;  
  25.             num2 = carry;  
  26.         } while (num2 != 0);  
  27.   
  28.         return num1;  
  29.     }  
  30. }  

面试题48:不能被继承的类

题目大致为:
    用C++设计一个不能被继承的类。
思路:
    在Java中只要把类定义为final就OK。Java和C++语言有差异的地方还有很多。
面试题49:把字符串转换成整数
面试题50:树中两个结点的最低公共祖先
面试题51:数组中重复的数字
面试题52:构建乘积数组
面试题53:正则表达式匹配
面试题54:
面试题55:

面试题56:链表中环的入口结点

题目大致为:
    一个链表中包含环,如何找出环的入口结点?
思路:

   对于上图中的链表,首先得判断是否有环存在,在环存在的情况下求出环中结点的个数,最后类似求链表的倒数第K个结点求出入口结点。这样的过程可以使用快慢指针的方式求解。
链表结构
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 链表的节点 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class ListNode {  
  10.     private int value;  
  11.     private ListNode next;  
  12.   
  13.     public ListNode(int value) {  
  14.         this.value = value;  
  15.     }  
  16.   
  17.     public ListNode(int value, ListNode next) {  
  18.         this.value = value;  
  19.         this.next = next;  
  20.     }  
  21.   
  22.     public void setValue(int value) {  
  23.         this.value = value;  
  24.     }  
  25.   
  26.     public void setNext(ListNode next) {  
  27.         this.next = next;  
  28.     }  
  29.   
  30.     public int getValue() {  
  31.         return this.value;  
  32.     }  
  33.   
  34.     public ListNode getNext() {  
  35.         return this.next;  
  36.     }  
  37.   
  38. }  

Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. /** 
  4.  * 面试题56:链表中环的入口结点 
  5.  *  
  6.  * @author dell 
  7.  *  
  8.  */  
  9. public class Item56 {  
  10.     public static void main(String args[]) {  
  11.         // 生成链表  
  12.         ListNode head = new ListNode(1);  
  13.         ListNode node_2 = new ListNode(2);  
  14.         ListNode node_3 = new ListNode(3);  
  15.         ListNode node_4 = new ListNode(4);  
  16.         ListNode node_5 = new ListNode(5);  
  17.         ListNode node_6 = new ListNode(6);  
  18.         head.setNext(node_2);  
  19.         node_2.setNext(node_3);  
  20.         node_3.setNext(node_4);  
  21.         node_4.setNext(node_5);  
  22.         node_5.setNext(node_6);  
  23.         node_6.setNext(node_3);  
  24.   
  25.         // 找到环的入口结点  
  26.         System.out.println("环的入口结点为:" + getEntry(head).getValue());  
  27.     }  
  28.       
  29.     /** 
  30.      * 求出环内结点的个数 
  31.      * @param head 
  32.      * @return 
  33.      */  
  34.     public static int numOfCycle(ListNode head) {  
  35.         // 链表是否存在  
  36.         if (head == null) {  
  37.             return -1;// -1表示不存在环  
  38.         }  
  39.   
  40.         // 建立快慢指针  
  41.         ListNode fastNode = head;  
  42.         ListNode slowNode = head;  
  43.   
  44.         int num = 0// 环中结点的个数  
  45.   
  46.         while (fastNode != null && slowNode != null) {  
  47.             if (fastNode.getNext() != null  
  48.                     && fastNode.getNext().getNext() != null) {  
  49.                 fastNode = fastNode.getNext().getNext();  
  50.             } else {  
  51.                 return -1;// -1表示不存在环  
  52.             }  
  53.             slowNode = slowNode.getNext();  
  54.             // 相遇表示存在环  
  55.             if (fastNode == slowNode) {  
  56.                 break;// 跳出循环  
  57.             }  
  58.         }  
  59.   
  60.         // 计算环中结点的个数  
  61.         num++;  
  62.         slowNode = slowNode.getNext();  
  63.         while (slowNode != fastNode) {  
  64.             slowNode = slowNode.getNext();  
  65.             num++;  
  66.         }  
  67.         return num;  
  68.     }  
  69.       
  70.     /** 
  71.      * 得到入口结点 
  72.      * @param head 
  73.      * @return 
  74.      */  
  75.     public static ListNode getEntry(ListNode head) {  
  76.         if (head == null) {  
  77.             return null;  
  78.         }  
  79.   
  80.         ListNode fastNode = head;  
  81.         ListNode slowNode = head;  
  82.         int k = numOfCycle(head);  
  83.         // 无环  
  84.         if (k == -1) {  
  85.             return null;  
  86.         }  
  87.   
  88.         // 快指针先走k步,这边是关键  
  89.         for (int i = 0; i < k; i++) {  
  90.             fastNode = fastNode.getNext();  
  91.         }  
  92.   
  93.         // 同时走  
  94.         while (fastNode != slowNode) {  
  95.             fastNode = fastNode.getNext();  
  96.             slowNode = slowNode.getNext();  
  97.         }  
  98.   
  99.         return fastNode;  
  100.     }  
  101. }  

面试题57:删除链表中重复的结点
题目大致为:
在一个排序的链表中,如何删除重复的结点?
思路:
原始的链表:

删除重复结点后的链表

链表中结点的删除,最关键的就是不能断链。在删除的过程中,被删除结点的前一个结点的指针必须保存,这样才不会断链,所以必须存在一个指针preNode。
面试题58:
面试题59:

面试题60:把二叉树打印成多行

题目大致为:
从上往下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
思路:
实际上就是二叉树的层次遍历问题,可以使用队列存储。
二叉树结构
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. public class BinaryTreeNode {  
  4.     private int value;  
  5.     private BinaryTreeNode left;  
  6.     private BinaryTreeNode right;  
  7.   
  8.     public BinaryTreeNode(int value) {  
  9.         this.value = value;  
  10.     }  
  11.   
  12.     public BinaryTreeNode(int value, BinaryTreeNode left, BinaryTreeNode right) {  
  13.         this.value = value;  
  14.         this.left = left;  
  15.         this.right = right;  
  16.     }  
  17.   
  18.     public int getValue() {  
  19.         return value;  
  20.     }  
  21.   
  22.     public void setValue(int value) {  
  23.         this.value = value;  
  24.     }  
  25.   
  26.     public BinaryTreeNode getLeft() {  
  27.         return left;  
  28.     }  
  29.   
  30.     public void setLeft(BinaryTreeNode left) {  
  31.         this.left = left;  
  32.     }  
  33.   
  34.     public BinaryTreeNode getRight() {  
  35.         return right;  
  36.     }  
  37.   
  38.     public void setRight(BinaryTreeNode right) {  
  39.         this.right = right;  
  40.     }  
  41.   
  42. }  

Java实现
[java] view plain copy
  1. package org.algorithm.pointtooffer;  
  2.   
  3. import java.util.LinkedList;  
  4. import java.util.Queue;  
  5.   
  6. /** 
  7.  * 面试题60:把二叉树打印成多行 
  8.  *  
  9.  * @author dell 
  10.  *  
  11.  */  
  12. public class Item60 {  
  13.     public static void main(String args[]) {  
  14.         // 构建二叉树  
  15.         BinaryTreeNode root = new BinaryTreeNode(8);  
  16.         BinaryTreeNode t1 = new BinaryTreeNode(6);  
  17.         BinaryTreeNode t2 = new BinaryTreeNode(10);  
  18.         BinaryTreeNode t3 = new BinaryTreeNode(5);  
  19.         BinaryTreeNode t4 = new BinaryTreeNode(7);  
  20.         BinaryTreeNode t5 = new BinaryTreeNode(9);  
  21.         BinaryTreeNode t6 = new BinaryTreeNode(11);  
  22.         root.setLeft(t1);  
  23.         root.setRight(t2);  
  24.         t1.setLeft(t3);  
  25.         t1.setRight(t4);  
  26.         t2.setLeft(t5);  
  27.         t2.setRight(t6);  
  28.         t3.setLeft(null);  
  29.         t3.setRight(null);  
  30.         t4.setLeft(null);  
  31.         t4.setRight(null);  
  32.         t5.setLeft(null);  
  33.         t5.setRight(null);  
  34.         t6.setLeft(null);  
  35.         t6.setRight(null);  
  36.         // 逐层打印  
  37.         printMulti(root);  
  38.     }  
  39.       
  40.     /** 
  41.      * 逐层打印 
  42.      * @param root根结点 
  43.      */  
  44.     public static void printMulti(BinaryTreeNode root) {  
  45.         Queue<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>();  
  46.         queue.add(root);  
  47.         int num = 1;// 表示当前lever层上的结点个数  
  48.         while (!queue.isEmpty()) {// 队列非空  
  49.             int nextNum = 0;// 临时变量,用来记录下一层的结点个数  
  50.             // 取出当前层并打印,随后加入下一层的结点  
  51.             for (int i = 0; i < num; i++) {  
  52.                 BinaryTreeNode tmp = queue.poll();// 取出队列头  
  53.   
  54.                 // 左孩子不为空  
  55.                 if (tmp.getLeft() != null) {  
  56.                     queue.add(tmp.getLeft());  
  57.                     nextNum++;  
  58.                 }  
  59.   
  60.                 // 右孩子不为空  
  61.                 if (tmp.getRight() != null) {  
  62.                     queue.add(tmp.getRight());  
  63.                     nextNum++;  
  64.                 }  
  65.                 System.out.print(tmp.getValue() + "\t");  
  66.   
  67.             }  
  68.             System.out.println();  
  69.             num = nextNum;  
  70.         }  
  71.     }  
  72.   
  73. }  

面试题61:
面试题62:
面试题63:
面试题64:
面试题65:
面试题66:
面试题67:
原创粉丝点击