[简单] 706. 设计哈希映射

https://leetcode-cn.com/problems/design-hashset/

我会写一些无脑得代码

class MyHashMap {


    class Node {
        int key;
        int value;

        Node(int key, int value) {
            this.key = key;
            this.value = value;
        }

        public int getKey() {
            return key;
        }

        public void setKey(int key) {
            this.key = key;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Node node = (Node) o;
            return key == node.key && value == node.value;
        }

        @Override
        public int hashCode() {
            return Objects.hash(key, value);
        }
    }


    private int iSize = 16;
    Node[] arr = new Node[iSize];
    int iListCount = 0;

    public MyHashMap() {
    }

    public void put(int key, int value) {
        if(iListCount + 1 > arr.length) {
            // 数据迁移;
            Node[] tempArr = new Node[arr.length];
            for (int m = 0; m <  arr.length; m++) {
                tempArr[m] = arr[m];
            }
            iSize *= 2;
            arr = new Node[iSize];
            // 拷贝回去.
            for (int m = 0; m <  tempArr.length; m++) {
                arr[m] = tempArr[m];
            }
        }

        boolean bExist = false;
        if(iListCount > 0) {
            for (int n = 0; n < iListCount; n++) {
                if(arr[n].getKey() == key) {
                    bExist = true;
                    // 进行值更新.
                    arr[n].setValue(value);
                    break;
                }
            }
        }

        if(!bExist) {
            arr[iListCount++] = new Node(key,value);
        }
    }

    public int get(int key) {
        int ret = -1;
        for (int n = 0; n < iListCount; n++) {
            if(arr[n].getKey() == key) {
                ret = arr[n].getValue();
                break;
            }
        }
        return ret;
    }

    public void remove(int key) {
        int index = -1;
        for (int n = 0; n < iListCount; n++) {
            if(arr[n].getKey() == key) {
                index = n;
                break;
            }
        }

        if(index != -1) {
            List<Node> lst = new ArrayList<>();// Arrays.asList(arr);

            for (int n = 0; n < iListCount; n++) {
                lst.add(arr[n]);
            }
            lst.remove(index);
            arr = new Node[iSize];
            for (int m = 0; m < lst.size(); m++) {
                arr[m] = lst.get(m);
            }
            iListCount--;
        }
    }
}
View Code

 

posted @ 2022-04-04 16:59  v大喵  阅读(20)  评论(0)    收藏  举报