面试题06. 从尾到头打印链表///面试题05. 替换空格///面试题04. 二维数组中的查找

 

 

 

public int[] reversePrint(ListNode head) {
        Stack<ListNode> stack = new Stack<>();

        ListNode temp = head;
        while(temp != null){
            stack.push(temp);
            temp = temp.next;
        }
        int[] ret = new int[stack.size()];
     //这里不能用stack.size(), //
for (int i = 0; i < stack.size(); ++ i){
      int size = stack.size()
      for(int i=0;i<size;++i){ ret[i]
= stack.pop().val; } return ret; }
//其中主要是java中stack的用法:https://www.cnblogs.com/xumz/p/7724934.html

 

 

 

public static String replaceSpace(String s) {
    //这里判断字符串是否为空,需要注意
    //这里s=" ",长度为2
if(s == null || s.length() == 0){ return ""; } //char和string的转换放在for里挺费时间的 char[] str = s.toCharArray(); char[] ret = new char[3 * str.length]; int size = 0; for(char c : str){ if (c == ' '){ ret[size++] = '%'; ret[size++] = '2'; ret[size++] = '0'; }else{ ret[size++] = c; } } return new String(ret, 0, size); }

 

 

 

 

解题思路

利用递增,剔除一列或一行。从右上或左下开始:
小于右上,剔除最右列;大于右上,剔除最上行。

//这道题算是打开了新的思路,比二分查找要好
public static boolean findNumberIn2DArray(int[][] matrix, int target) {
        //首先判断二维数组是否为空,需要注意一下
        if(matrix == null || matrix.length == 0 ||
                (matrix.length == 1 && matrix[0].length == 0)){
            return false;
        }
        int rowLength = matrix.length;
        int colLength = matrix[0].length;

        int i = 0, j = colLength - 1;
        while (i < rowLength && j >= 0){
            if (matrix[i][j] == target)
                return true;
            else if (matrix[i][j] > target){
                --j;
            }
            else ++i;
        }
        return false;
    }

 

posted @ 2020-04-10 11:13  贱人郭  阅读(126)  评论(0编辑  收藏  举报