分享两道面试题

1. 二维数组

现有一个n*n的二维正整数数组nums,每行元素保证递增,每列元素保证递增,求某正整数x是否存在于该二维数组中,需要尽量优化时间和空间复杂度;

原题

/**
	*	
     * <b>注意! 本题不要遍历二维数组. 要求时间复杂度严格低于n^2, 否则视为不得分 </b>
     *
     * 现有一个n*n的二维正整数数组nums,每行元素保证递增,每列元素保证递增,求某正整数x是否存在于该二维数组中,需要尽量优化时间和空间复杂度;
     * @param int[][] nums
     * @param int x 目标数
     * @return boolean
     */
public static boolean searchMatrix(int[][] nums, int x) {
    
    
			//TODO
        return false;
    }

解析:本体已经注明了不希望我们进行遍历二维数组进行查找,而且还要保持更快的查询速度,介于此,我们可以使用二分法进行查询

public static boolean searchMatrix(int[][] nums, int x) {
    
    
        if (nums == null || nums[0] == null) return false;
        int i = 0, j = nums[0].length - 1;
        while (i < nums.length && j >= 0) {
    
    
            if (nums[i][j] == x) return true;
            else if (nums[i][j] > x) --j;
            else ++i;
        }
        return false;
    }

2.二叉树

给定一个二叉树, 检查它是否是镜像对称的

原题

/**
     * 给定一个二叉树, 检查它是否是镜像对称的
     * 例如以下是镜像对称的
     *      1
     *     / \
     *    2   2
     *   / \ / \
     *  3  4 4  3
     *
     * 下面这个则不是镜像对称的
     *      1
     *     / \
     *    2   2
     *     \   \
     *      3   3
     *
     * TreeNode类的定义:
     *
     * @param TreeNode 一颗二叉树
     * @return boolean 是否是对称的
     */

    // 以下给出TreeNode类, 请勿修改
    static class TreeNode {
    
    
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
    
     val = x; }
    }

    public static boolean isTreeSymmetric(TreeNode root) {
    
    
        //TODO your code goes here...
        return false;
    }

解析:通过镜像树的对称性质可以发现,节点的左节点比较的是同层对称节点的右节点,节点的右节点比较的是同层对称节点的左节点。所以我们可以通过递归来解决。

 static class TreeNode {
    
    
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
    
     val = x; }
    }

    public static boolean isTreeSymmetric(TreeNode root) {
    
    
        //TODO your code goes here...
        return isSame(root, root);
    }
    public static boolean isSame(TreeNode t1,TreeNode t2){
    
    
        if (t1 == null && t2 == null) return true;
        if (t1 == null || t2 == null) return false;
        return t1.val == t2.val && isSame(t1.left,t2.right) && isSame(t1.right,t2.left);
    }

猜你喜欢

转载自blog.csdn.net/jxysgzs/article/details/114019472