码迷,mamicode.com
首页 > 其他好文 > 详细

706. Design HashMap - LeetCode

时间:2018-07-26 22:07:14      阅读:441      评论:0      收藏:0      [点我收藏+]

标签:this   分享图片   init   you   最大   shm   hash   always   ems   

Question

706. Design HashMap

技术分享图片

Solution

题目大意:构造一个hashmap

思路:讨个巧,只要求key是int,哈希函数选择f(x)=x,规定key最大为1000000,那构造一个1000000的数组

Java实现:

class MyHashMap {

    int[] table;
    
    /** Initialize your data structure here. */
    public MyHashMap() {
        table = new int[1000000];
        Arrays.fill(table, -1);
    }
    
    /** value will always be non-negative. */
    public void put(int key, int value) {
        table[key] = value;
    }
    
    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    public int get(int key) {
        return table[key];
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    public void remove(int key) {
        table[key] = -1;
    }
}

/**
 * Your MyHashMap object will be instantiated and called as such:
 * MyHashMap obj = new MyHashMap();
 * obj.put(key,value);
 * int param_2 = obj.get(key);
 * obj.remove(key);
 */

参考别人的

class MyHashMap {
    final Bucket[] buckets = new Bucket[10000];

    public void put(int key, int value) {
        int i = idx(key);
        if (buckets[i] == null)
            buckets[i] = new Bucket();
        ListNode prev = find(buckets[i], key);
        if (prev.next == null)
            prev.next = new ListNode(key, value);
        else prev.next.val = value;
    }

    public int get(int key) {
        int i = idx(key);
        if (buckets[i] == null)
            return -1;
        ListNode node = find(buckets[i], key);
        return node.next == null ? -1 : node.next.val;
    }

    public void remove(int key) {
        int i = idx(key);
        if (buckets[i] == null) return;
        ListNode prev = find(buckets[i], key);
        if (prev.next == null) return;
        prev.next = prev.next.next;
    }

    int idx(int key) { return Integer.hashCode(key) % buckets.length;}

    ListNode find(Bucket bucket, int key) {
        ListNode node = bucket.head, prev = null;
        while (node != null && node.key != key) {
            prev = node;
            node = node.next;
        }
        return prev;
    }
}

class Bucket {
    final ListNode head = new ListNode(-1, -1);
}

class ListNode {
    int key, val;
    ListNode next;

    ListNode(int key, int val) {
        this.key = key;
        this.val = val;
    }
}

706. Design HashMap - LeetCode

标签:this   分享图片   init   you   最大   shm   hash   always   ems   

原文地址:https://www.cnblogs.com/okokabcd/p/9374563.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!