剑指Offer的一些数据结构面试题目

1.一个二维数组,每一行从左到右递增,每一列从上到下递增.输 入一个二维数组和一个整数,判断数组中是否含有整数。

代码演示
package ArrayTest;

public class Find {

    public static boolean find (int[] [] array, int number) {
        if(array==null) {
            return false;
        }
        /**
         * 从第一个二维数组的最大值开始查找
         */
        int column = array[0].length-1;
        int row = 0;
        while(row<array.length &&column>=0) {
            if(array[row][column]==number) {
                return true;
            }else if(array[row][column]>number) {
                System.out.println("column:"+column);
                column--;
            }else {
                System.out.println("row:"+row);
                row++;
            }
            
        }
        return false;
    }
    
    public static void main(String[] args) {
        int[][] testarray = new int[4][4];
        testarray[0][0] = 1;
        testarray[0][1] = 2;
        testarray[0][2] = 8;
        testarray[0][3] = 9;
        testarray[1][0] = 2;
        testarray[1][1] = 4;
        testarray[1][2] = 9;
        testarray[1][3] = 12;
        testarray[2][0] = 4;
        testarray[2][1] = 7;
        testarray[2][2] = 10;
        testarray[2][3] = 13;
        testarray[3][0] = 6;
        testarray[3][1] = 8;
        testarray[3][2] = 11;
        testarray[3][3] = 15;
        System.out.println(find(testarray, 6));
    }
}

2.请实现一个函数,把字符串中的每个空格替换成“%20”。

代码演示

package StringTest;

public class ReplaceBlank {

    public static void main(String[] args) {
        String s = "We are happy";
        System.out.println(replaceBlank(s));
    }
    
    public static String  replaceBlank(String s) {
        if(s==null||"".equals(s)) {
            return null;
        }
        StringBuffer sbuf = new StringBuffer();
        for(int i=0;i<s.length();i++) {
            if(s.charAt(i)==' ') {
                sbuf.append("%");
                sbuf.append("2");
                sbuf.append("0");
            }else {
                sbuf.append(String.valueOf(s.charAt(i)));
            }
        }
        return new String(sbuf);
    }
}

猜你喜欢

转载自www.cnblogs.com/Mr-RanX/p/11462826.html