Java版剑指Offer+思路解析(1-5)

牛客刷题-剑指Offer(1-5)

1、二维数组中的查找

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

设计思路:

1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16

如上表:先找到一个好比较的点,二维数组中左上角的1点往下或往右都比他大,判断起来往下走还是往右走没得选择,同理右下角也是一样;要把横着走还是竖着走区分开,所以选择右上角13或者左下角4来判断,这里我选择右上角13来判断,小于往左走,大于往下走。时间复杂度O(mn),空间复杂度O(1)

public class Solution {
    public boolean Find(int target, int [][] array) {
        int r = 0;				    //数组行
        int c = array[0].length-1;	 //数组列
        while(r < array.length && c >= 0){
            if(target < array[r][c])
                c--;
            else if(target > array[r][c])
                r++;
            else
                return true;
        }
        return false;	//没找到返回false
    }
}

2、替换空格

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

设计思路1:使用StringBuffer中的方法可以简单实现,先返回第一个空格下标索引值,判断是否获取成功(不为-1),删除当前位置的值,在当前位置添加“%20”,再获取空格下标......

public class Solution {
    public String replaceSpace(StringBuffer str) {
    	int i=str.indexOf(" ");
		while(i>=0) {
			str.deleteCharAt(i);
			str.insert(i, "%20");
			i=str.indexOf(" ",i);
		}
		return str.toString();
    }
}

设计思路2:使用char[],将str转换成char[] ch1,先获取ch1中空格的数量num,创建新字符数组长度为str.length+num*2的ch2,将ch1中的值依次添加到ch2中,判断是否是空格,为空格依次添加‘%’,‘2’,‘0’。

public class Solution {
    public String replaceSpace(StringBuffer str) {
    	char[] ch1 = str.toString().toCharArray();
	        int num = 0;
	        for(int i =0; i<ch1.length; i++){
	            if(ch1[i]==' '){
	                num++;
	            }
	        }
	        char[] ch2 = new char[2*num + ch1.length];
	        int len = 0;
	        for(int i=0; i<ch1.length; i++){
	            if(ch1[i] != ' '){
	                ch2[len++] = ch1[i];
	            }else{
	                ch2[len++] = '%';
	                ch2[len++] = '2';
	                ch2[len++] = '0';
	            }
	        }
        return String.valueOf(ch2);
    }
}

3、从尾到头打印链表

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

设计思路1:使用递归

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

设计思路2:使用栈

import java.util.Stack;
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack = new Stack<>();
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        ArrayList<Integer> list = new ArrayList<>();
        while (!stack.isEmpty()) {
            list.add(stack.pop());
        }
        return list;        
    }
}

4、重建二叉树

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

设计思路:递归调用,将左右子树看成一个新树,根据前序遍历序列可知第一个节点就是根节点,在中序遍历中根节点左面的就是左子树,根节点右边的就是右子树......以此类推。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
          TreeNode root=reConstructBTree(pre,0,pre.length-1,in,0,in.length-1);
          return root;
     }
      private TreeNode reConstructBTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {
            TreeNode root=null;
            if(startPre<=endPre&&startIn<=endIn){
                root=new TreeNode(pre[startPre]);
                for(int i=startIn;i<=endIn;i++)
                    if(in[i]==pre[startPre]){
                        root.left=reConstructBTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
                        root.right=reConstructBTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
                    }
            }
            return root;
        }
}

5、用两个栈实现队列

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

设计思路:使用两个栈1和2,栈1负责进,栈2负责出;队列先进先出,栈后进先出;可以将栈1中的数据压入栈2中再进行弹出,实现先进先出;

import java.util.Stack;

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.isEmpty()){
            while(!stack1.isEmpty()){
                int node=stack1.pop();
                stack2.push(node);
            }
        }
        return stack2.pop();
    }
}
posted @ 2020-08-10 00:34  枫叶火火  阅读(112)  评论(0)    收藏  举报