Design a HashMap without using any built-in hash table libraries.
Implement the MyHashMap class:
MyHashMap() initializes the object with an empty map. void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value. int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key. void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.
classPair { int key; int value; publicPair(int k, int v){ key = k; value = v; } publicintgetKey(){ return key; } publicintgetValue(){ return value; } publicvoidsetValue(int v){ value = v; } }
/** * 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); */
问题 Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.
classSolution { publicintthreeSumMulti(int[] arr, int target) { //enumberate every element and put them into the map HashMap<Integer, Long> map = newHashMap<Integer, Long>(); longcount=0; for ( int num : arr ){ if (!map.containsKey(num)){ map.put(num, (long)1); } else{ map.put(num, map.get(num)+1); } } //traverse whole elements and select three numbers for ( int a : map.keySet() ){ longtotalA= map.get(a); for (int b : map.keySet()){ longtotalB= map.get(b); if ( a == b ){ if (totalB < 2){ continue; } totalB = totalB - 1; }
intc= target - a - b; if ( map.containsKey(c) ){ longtotalC= map.get(c); longtotal=0; if ( a == b && b == c ){ total = totalA * totalB * ( totalC - 2 ) ; } elseif ( b == c || a == c ){ total = totalA * totalB * ( totalC - 1 ) ; } else{ total = totalA * totalB * totalC; } if ( total > 0 ){ count += total; }
问题描述 Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.