您的位置:首页 > 职场人生

剑指Offer第二章面试题(Java版)

2015-09-04 21:40 627 查看

面试题2:实现单例模式

/**
 * 静态内部类实现单例模式
 * @author liguodong
 */
public class Demo02 {
    private static class Demo02ClassInstance
    {
        private static final Demo02 instance = new Demo02();
    }

    private Demo02(){
    }

    //方法没同步,调用效率高。
    public static Demo02 getInstance(){
        return Demo02ClassInstance.instance;
    }
}


注:

线程安全,调用效率高,又可以延时加载

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

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

public class Solution {
    public boolean Find(int [][] array,int target) {
        int rows = array.length;
         int cols = array[0].length;

         if(array!=null&&rows>=0&&cols>=0){
             int row=0;
             int col=cols-1;
             while(row<rows&&col>=0){
                 if(array[row][col]==target){
                     return true;
                 }else if(array[row][col]<target){
                     row++;
                 }else {
                    col--;
                }
             }
         }  
         return false;
    }
}


注:

可以选取左上角或者右下角作为初始点。

面试题4:替换空格

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

public class Solution {
    public String replaceSpace(StringBuffer str) {
        char[] array = str.toString().toCharArray();

        int lenAfter = 0;
        int zeronum=0;
        for (int i = 0; i < array.length; i++) {
            if(array[i]==' '){
                zeronum++;
            }
        }
        lenAfter = array.length + zeronum*2;
        char[] arrayafter = new char[lenAfter];
        lenAfter--;
        for (int i = array.length-1; i >=0; i--) {
            if(array[i]==' '){
                arrayafter[lenAfter] = '0';
                lenAfter--;
                arrayafter[lenAfter] = '2';
                lenAfter--;
                arrayafter[lenAfter] = '%';
                lenAfter--;
            }
            else {
                arrayafter[lenAfter] = array[i];
                lenAfter--;
            }

        }
        String strafter = new String(arrayafter);

        return strafter;
    }
}


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

输入一个链表,从尾到头打印链表每个节点的值。

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
       Stack<ListNode> stack = new Stack<>();
        ArrayList<Integer> arrayList = new ArrayList<>();
        if (listNode!=null) {
            while(listNode.next!=null){
                stack.push(listNode);
                listNode = listNode.next;
            }
            stack.push(listNode);
        }

        while (!stack.isEmpty()) {
            arrayList.add(stack.pop().val);
        }
        return arrayList;
    }
}


面试题6: 重建二叉树

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




/**
 * 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){
            return null;
        }
        return reConstructBinaryTreeCore(pre,0,pre.length-1,in,0,in.length-1);
    }

    public TreeNode reConstructBinaryTreeCore
    (int[] pre,int startpre,int endpre,int[] in,int startin,int endin){
        //前序遍历
        int rootValue = pre[startpre];
        //构建根节点
        TreeNode root = new TreeNode(rootValue);
        root.left = root.right = null;

        if(startpre==endpre){
            if (startin==endin&&pre[startpre]==in[startin]) {
                return root;
            }else {//无效输入
                try {
                    throw new Exception();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        //中序遍历
        int rootIndex = startin;
        while (rootIndex<=endin && in[rootIndex]!=rootValue) {//在中序中找到root值
            ++rootIndex;
        }

        if(rootIndex > endin){//无效输入
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //左子树长度   3
        int leftLen = rootIndex-startin;

        //左子树的下标  3
        int leftPreEnd = startpre+leftLen;

        if(leftLen>0){
            //构建左子树   1  3      0  2
            root.left = reConstructBinaryTreeCore
                    (pre, startpre+1, leftPreEnd, in, startin, rootIndex-1);    
        }
        if(leftLen<endpre-startpre){
            //构建右子树   4  7      4  7
            root.right =  reConstructBinaryTreeCore
                    (pre, leftPreEnd+1, endpre, in, rootIndex+1, endin);
        }
        return root;
    }
}


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

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

/article/1324513.html

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

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非递减序列的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。

import java.util.ArrayList;
public class Solution {
    /**
     * 旋转数组的最小数字
     */
    public int minNumberInRotateArray(int [] array) {
        if(array==null||array.length==0){
            return  0;
        }

        int low=0;
        int high=array.length-1;
        int minIndex = low;

        //array[low]<array[high]  表明是升序,直接返回最低下标
        while(array[low]>=array[high]){

            //表明最大值与最小值在一起
            if(high-low==1){
                minIndex = high;
                break;
            }

            minIndex = (low+high)/2;

            //如果下标为low、high、minIndex指向的三个数字相等,则无法判断中间的数字是
            //位于前面的子数组还是后面的子数组
            //eg:1 0 1 1 1  ---  1 1 1 0 1
            if(array[low]==array[minIndex]&&array[minIndex]==array[high]){
                return MinInorder(array, low, high);
            }

            //表明最小值在后半段
            if(array[minIndex]>=array[low]){
                low = minIndex;
            }else if(array[minIndex]<=array[high]){//表明最小值在前半段
                high = minIndex;
            }  
        }
        return array[minIndex];
    }

    public int MinInorder(int[] numbers,int low,int high){
        int result = numbers[low];
        for (int i = low+1; i <= high; i++) {
            if(result>numbers[i]){
                result = numbers[i];
                break;
            }
        }
        return result;
    }
}


面试题9: 斐波那契数列

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。

public class Solution {
    public int Fibonacci(int n) {

        if(n==0||n==1){
            return n;
        }
        int a = 0;
        int b = 1;
        int temp=0;
        for (int i = 2; i <= n; i++) {
            temp = a+b;
            a = b;
            b = temp;
        }
        return temp;
    }
}


注:

避免了递归方式的重复计算。

附加:

变态跳台阶

一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

//1 2 4 8 16
public class Solution {
    public int JumpFloorII(int target) {
        if(target==1||target==2){
            return target;
        }
        int a = 1;
        int b = 2;
        int sum=0;
        int temp = 0;
        temp = a+b;//temp用于保存前n-1项的数据的总和
        for (int i = 3; i <= target; i++) {
            temp = sum+temp;//前n-1项的总和等于前n-2项的总和加上n-1项
            sum = temp+1;
        }
        return sum;
    }
}


矩形覆盖

我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

//0 1 1 2 3 5
public class Solution {
    public int RectCover(int target) {
        if(target==0||target==1){
            return 1;
        }
        int a = 1;
        int b = 1;
        int temp=0;
        for (int i = 2; i <= target; i++) {
            temp = a+b;
            a = b;
            b = temp;
        }
        return temp;
    }

}


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

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

public class Solution {
    public int NumberOf1(int n) {
        int num=0;
        while(n!=0){
            n = n&(n-1);
            num++;
        }
        return num;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: