注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
本人Java菜niao一枚,最近刚开始用Java刷题。刚学了一下MIT6.006的Hash Map的部分,就来练了一下力扣的706 (https://leetcode.com/problems/design-hashmap/)练练手。结果submit以后发现有wrong answer。苦思冥想了一整天还是没搞清楚自己错在哪里,跪求地里的高手指点一二。有指点必加米。先谢谢了!
- class ListNode {
- public int key;
- public int value;
- public ListNode next;
-
- public ListNode(int key, int value) {
- this.key = key;
- this.value = value;
- }
- }
- class MyHashMap {
- private ListNode[] arr;
- private int divisor = 2069;
- /** Initialize your data structure here. */
- public MyHashMap() {
- this.arr = new ListNode[divisor];
- }
-
- /** value will always be non-negative. */
- public void put(int key, int value) {
- int k = key%this.divisor;
- if (arr[k]==null){
- arr[k] = new ListNode(key, value);
- } else {
- ListNode cur = arr[k], prev = null;
- while (cur!=null){
- if (cur.key == key) {
- cur.value = value;
- return;
- }
- prev = cur;
- cur = cur.next;
- }
- prev.next = new ListNode(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) {
- int k = key%this.divisor;
- if (arr[k]==null) {
- return -1;
- } else {
- ListNode cur = arr[k];
- while (cur!=null) {
- if (cur.key == key) {
- return cur.value;
- }
- cur = cur.next;
- }
- }
-
- return -1;
- }
-
- /** Removes the mapping of the specified value key if this map contains a mapping for the key */
- public void remove(int key) {
- int k = key%this.divisor;
- if (arr[k]!=null) {
- ListNode cur = arr[k], prev = null;
- while (cur!=null) {
- if (cur.key == key) {
- if (prev!=null) {
- prev.next = cur.next;
- } else {
- arr[k] = null;
- }
- cur = null;
- break;
- }
- prev = cur;
- cur = cur.next;
- }
- }
- }
- }
- /**
- * 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);
- */
复制代码
|