炸炸熊 - Day1

137 阅读2分钟

写代码时来一杯白桃乌龙茶,桃气满满:item.taobao.com/item.htm?sp…

基础

HashMap

1.7

数组 + 链表

1.8

数组 + 链表 + 红黑树

扩容

  • 负载因子:0.75

    数量大于某长度开始扩容

    冲突 与 内存空间之间的权衡

  • 扩容函数 2 的幂次

    方便进行位运算 h & (length-1)

线程不安全

ReHash 由于没有同步机制,会导致线程不安全。

例如:同时 Put 操作,会导致数据的丢失

重写

hashcode 是根据对象的内存地址进行计算的,因此在存储进 HashMap 时,对相同的对象进行覆盖操作,需要重写 hashcode 函数,来计算是否相同

CocurrentHashMap

快速失败与安全失败

快速失败

java.util包下的集合类是fail-fast的,快速失败

在使用迭代器的时候,快速失败的集合类是会抛出ConcurrentModificationException异常

安全失败

java.util.concurrent 包下的类都是安全失败,比如:ConcurrentHashMap

在使用迭代器的时候,安全失败的集合类是不会会抛出ConcurrentModificationException异常

总结:失败的原因,是迭代器在迭代过程中计算 modCount 是否符合预期,如果修改过则不符预期抛出异常。快速失败的类,直接在原来的集合上操作会修改 modCount。安全失败的类,先进行拷贝因此多线程操作不会发现变化。

Leetcode

107-binary-tree-level-order-traversal-ii

题目:按层遍历二叉树。

思路1: 先从上到下遍历二叉树存储到数组中,最后将数组倒序存储

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

    public List<List<Integer>> levelOrderBottom(TreeNode root) {

        if (root == null) {
            return new ArrayList<>();
        }
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<TreeNode> list = new ArrayList<TreeNode>();
        list.add(root);
        while(list.size() > 0) {
            List<Integer> nums = new ArrayList<Integer>();
            List<TreeNode> children = new ArrayList<>();
            for (int i = 0; i<list.size(); i++) {
                TreeNode node = list.get(i);
                nums.add(node.val);
                if (node.left != null) {
                    children.add(node.left);
                }
                if (node.right != null) {
                    children.add(node.right);
                }
                System.out.print(nums.get(i));
            }
            list = children;

            result.add(nums);
            System.out.println("nums" + nums.toString());
        }
        List<List<Integer>> out = new ArrayList<>();
        for (int i = 0; i < result.size(); i ++) {
            out.add(result.get(result.size() -1 - i));
        }
        return out;    
    }
}