剑指offer代码记录

1、二维数组查找

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

2、从头到尾打印链表

import java.util.ArrayList;

public class Solution {
    public ArrayList printListFromTailToHead(ListNode listNode) {
        ArrayList arr = new ArrayList();
        while (listNode != null) {
            arr.add(listNode.val);
            listNode = listNode.next;
        }
        if (arr.size() < 1) return arr;

        ArrayList att = new ArrayList();
        if (arr.size() != 0) {
            for (int j = arr.size() - 1; j >= 0; j--) {
                att.add(arr.get(j));
            }
        }
        return att;
    }
}

3、重建二叉树

public class Solution {
    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        TreeNode root = reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
        return root;
    } 
    private TreeNode reConstructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) {
        if (startPre > endPre || startIn > endIn)
            return null;
        TreeNode root = new TreeNode(pre[startPre]);
        for (int i = startIn; i <= endIn; i++)
            if (in[i] == pre[startPre]) {
                root.left = reConstructBinaryTree(pre, startPre + 1, startPre + i - startIn, in, startIn, i - 1);
                root.right = reConstructBinaryTree(pre, i - startIn + startPre + 1, endPre, in, i + 1, endIn);
                break;
            }
        return root;
    }
}

4、跳台阶

public class Solution {
    public int JumpFloor(int target) {
        if(target==1) return 1;
        if(target==2) return 2;
        if(target>=2) return JumpFloor(target-1)+JumpFloor(target-2);
        return 0;
    }
}

5、变态跳台阶

public class Solution {
    public int JumpFloorII(int target) {
        if (target == 1)
            return 1;
        else if (target == 2) {
            return JumpFloorII(target - 1) + 1;
        } else
            return (int) Math.pow(2, target - 2) *2;
    }
}

6、矩形覆盖

public class Solution {
    public int RectCover(int target) {
        if(target<=0){
            return 0;
        }else if(target<=2){
            return target;
        }else{
            return RectCover(target-1)+RectCover(target-2);
        }
    }
}

 

你可能感兴趣的:(剑指offer代码记录)