java 剑指offer

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27667379/article/details/81535234

刷题中~不断更新~

第一题:二维数组中的查找

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

代码

public class Solution {
public boolean Find(int target, int[][] array) {
            for (int i = 0;i < array.length ;i++ ) {
                for (int j=0; j < array[0].length;j++) {
                    if (target == array[i][j]) {
                        return true;
                    }
                }
            }
            return false;
        }
}

比较暴力解决,后看见一个好办法:利用二分查找,时间复杂度:O(2n) 。

传送门:https://blog.csdn.net/FlushHip/article/details/78914719

第二题:

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

感觉这题挺简单的直接就能返回。

代码:

    public class Solution {
        public String replaceSpace(StringBuffer str) {
            return str.toString().replaceAll(" ","%20");
        	
        }
    }

第三题

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

代码:

import java.util.ArrayList;
import java.util.Collections;
public class Solution {
      public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> al = new ArrayList<Integer>();
        if (listNode != null) {
            al.add(listNode.val);
            ListNode nextnode = listNode.next;
            while (nextnode != null) {
                al.add(nextnode.val);
                nextnode = nextnode.next;
            }
            Collections.reverse(al);
        }
        return al; 
    }
}

第四题

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

代码:

 public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if (pre.length==0||in.length==0){
            return null;
        }
        TreeNode node = new TreeNode(pre[0]);
        for (int i =0;i<in.length;i++){
            if (in[i]==pre[0]){
                 node.left=reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));
                 node.right=reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),   Arrays.copyOfRange(in,i+1,in.length));
            }
        }
        return node;
    }

真是小白一个啊,每题都得看看别人的思路,再不好好学习,无工作啦~

第五题

题目描述

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

代码:

public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();

        public void push(int node) {
            stack1.push(node);

        }

        public int pop() {
          
            if (stack2.empty()) {
                while (!stack1.empty()) {
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();

        }
    }

push为进栈,pop为出栈操作。

猜你喜欢

转载自blog.csdn.net/qq_27667379/article/details/81535234