剑指offer题目汇总

二维数组中的查找

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

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

替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
public class Solution {
    public String replaceSpace(StringBuffer str) {
        return str.toString().replaceAll(" ","%20");
    }
}

从尾到头打印链表

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
          if(listNode == null){
            return list;
          }
        Stack<Integer> stack = new Stack<>();
        
        while(listNode != null){
            //栈用push(),队列用add()
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        while(!stack.empty()){
            list.add(stack.pop());
        }
        return list;
    }
}

猜你喜欢

转载自www.cnblogs.com/linliquan/p/11696431.html
今日推荐