刷题03——剑指offer2-5

面试题2:实现Singleton模式

题目:设计一个类,我们只能生成该类的一个实例。

一、加同步锁前后两次判断实例是否存在(懒汉)

public class Singleton {
    private Singleton(){}
    private static Singleton instance;
    public static Singleton getInstance(){
        if(instance == null) {
            synchronized(Singleton.class) {
                if(instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

二、利用静态构造函数(饿汉)

public class Singleton {
    private Singleton(){}
    private static Singleton instance = new Singleton();
    public static Singleton getInstance() {
        return instance;
    }
}

三、静态类内部加载

public class Singleton {
    private Singleton() {}
    public static Singleton getInstance() {
        return SingletonFactory.instance;
    }
    private static class SingletonFactory{
        private static Singleton instance = new Singleton();
    }
}

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

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

public class Solution {
    public boolean Find(int target, int [][] array) {
        boolean found = false;
        if(array != null) {
            int row = 0;
            int col = array[0].length - 1;
            while(row < array.length && col >= 0) {
                if(array[row][col] == target) {
                    found = true;
                    break;
                } else if(array[row][col] > target) {
                    col--;
                } else if(array[row][col] < target) {
                    row++;
                }
            }
        }
        return found;
    }
}

面试题5:替换空格

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

public class Solution {
    public String replaceSpace(StringBuffer str) {
    	int spaceNum = 0;
        for(int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == ' ') {
                spaceNum++;
            }
        }
        int oldIndex = str.length() - 1;
        int newIndex = str.length() + 2 * spaceNum - 1;
        str.setLength(newIndex + 1);
        for(; oldIndex >= 0 && newIndex >= 0 && spaceNum > 0; oldIndex--) {
            if(str.charAt(oldIndex) == ' ') {
                str.setCharAt(newIndex--, '0');
                str.setCharAt(newIndex--, '2');
                str.setCharAt(newIndex--, '%');
                spaceNum--;
            } else {
                str.setCharAt(newIndex--, str.charAt(oldIndex));
            }
        }
        return str.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/b515833/article/details/87868956