手撕代码

1、筛选数组arr中重复的元素,考虑时间复杂度。

时间复杂度为O(n)

package writtenTest01;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//手写代码:筛选数组arr中重复的元素,考虑时间复杂度。
public class filterDuplicateElements {

    public static void main(String[] args) {
        int[] arr = { 1, 1, 3, 4, 6, 6, 3 };
        List<Integer> res = duplicate(arr);
        System.out.println(res.toString());
    }

    public static List<Integer> duplicate(int[] arr) {
//a数组用来存放结果,b数组用来存放arr中每个元素的个数
int[] b = new int[arr.length]; List<Integer> list = new ArrayList<>();
//遍历arr,如果以arr中元素为下标的的b元素已存在,则该b元素加1,否则设置为1
for (int i = 0; i < arr.length; i++) { if (b[arr[i]] == 0) { b[arr[i]] = 1; continue; } b[arr[i]]++; } int m = 0; for (int i = 0; i < b.length; i++) { if (b[i] > 1) { list.add(i); } } return list; } }

 2、请你说一下BST的特点,并手写代码判断一棵树是不是BST

BST(二叉排序树):

1、每个结点都有一个作为搜索依据的关键码,所有结点的关键码不同

2、左子树上所有结点的关键码小于根节点的关键码

3、右子树所有结点的关键码大于根节点的关键码

4、左子树和右子树也是BST

判断一棵树是不是BST

class Node {
int data;
Node left;
Node right;
}
public class BSTChecker {
private static int lastVisit = Integer.MIN_VALUE;
public static boolean isBST(Node root) {
if(root == null) return true;


boolean judgeLeft = isBST(root.left); // 先判断左子树


if(root.data >= lastVisit && judgeLeft) { // 当前节点比上次访问的数值要大

lastVisit = root.data;
} else {
return false;
}


boolean judgeRight = isBST(root.right); // 后判断右子树

return judgeRight;
}
}

 3、两个平衡二叉树合并是怎么做的

// 首先,将两棵树分别展开为有序链表

public TreeNode prev = null;
public void BSTtoLinkedList(TreeNode root) {
if (root == null) return;
BSTtoLinkedList(root.left);
if (prev != null) {
prev.right = root;
prev.left = null;
}
prev = root;
BSTtoLinkedList(root.right);
}

//然后将两个有序链表合并

    
public TreeNode MergeTwoLinkedList(TreeNode n1, TreeNode n2) {
TreeNode head = new TreeNode();
while (n1 != null && n2 != null) {
if (n1.val < n2.val) {
head.right = n1;
n1 = n1.right;
} else {
head.right = n2;
n2= n2.right;
}
head = head.right;
}
if (n1 != null) {
head.right = n1;
head = head.right;
}
if (n2 != null) {
head.right = n2;
head = head.right;
}
return head.right;
}

4、求全体二叉树节点最大值

public int maxTreeNode(TreeNode root) {
if (root.left == null && root.right == null) {
return root.val;
} else {
if (root.left != null && root.right != null) {
return root.val > maxTreeNode(root.left) ? (root.val > maxTreeNode(root.right) ? root.val
: maxTreeNode(root.right))
: (maxTreeNode(root.left) > maxTreeNode(root.right) ? maxTreeNode(root.left)
: maxTreeNode(root.right));
} else if (root.left == null && root.right != null) {
return root.val > maxTreeNode(root.right) ? root.val
: maxTreeNode(root.right);
} else {
return root.val > maxTreeNode(root.left) ? root.val
: maxTreeNode(root.left);
}
}
}

 

posted @ 2020-06-30 09:44  我们村里的小花儿  阅读(164)  评论(0编辑  收藏  举报