Hash Tables

Run Settings
LanguageJava
Language Version
Run Command
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; class Main { // My own Hash Table implementation // int length; // ArrayList<KeyValue>[] data; // public HashTable(int size) { // data = new ArrayList[size]; // length = 0; // } // public int _hash(String key) { // int hash = 0; // for(int i = 0; i < key.length(); i++) { // hash = (hash + key.codePointAt(i) * i) % data.length; // } // return hash; // } // public void set(String key, int value) { // int address = _hash(key); // if(data[address] == null) { // ArrayList<KeyValue> arrayAtAddress = new ArrayList<>(); // data[address] = arrayAtAddress; // length++; // } // KeyValue pair = new KeyValue(key, value); // data[address].add(pair); // } // public Integer get(String key) { // int address = _hash(key); // ArrayList<KeyValue> bucket = data[address]; // if(bucket != null) { // for(KeyValue keyValue : bucket) { // if(keyValue.getKey().equals(key)) { // return keyValue.getValue(); // } // } // } // return null; // } // public String[] keys() { // ArrayList<KeyValue>[] bucket = data; // String[] keysArray = new String[length]; // int count = 0; // for(ArrayList<KeyValue> keyValues : bucket) { // if(keyValues != null) { // keysArray[count] = keyValues.get(0).getKey(); // count++; // } // } // return keysArray; // } // First Recurring Character // brute force // public static int firstRecurringNumber(int[] array) { // for(int i = 0; i < array.length; i++) { // for(int j = i + 1; j < array.length; j++) { // if(array[i] == array[j]) { // return array[i]; // } // } // } // return -1; // } // HashMap public static int firstRecurringNumber(int[] array) { HashSet<Integer> map = new HashSet<>(); for(int i = 0; i < array.length; i++) { if(map.contains(array[i])) { return array[i]; } else { map.add(array[i]); } } return -1; } public static void main(String[] args) { System.out.println("Hello World!"); // Hashtable implementation // HashTable hashTable = new HashTable(50); // hashTable.set("grapes", 1200); // hashTable.set("apple", 1500); // System.out.println("Grapes" + hashTable.get("grapes")); // System.out.println("Apple" + hashTable.get("apple")); // First Recurring Character int[] array = {2, 2}; System.out.println(firstRecurringNumber(array)); } }
Editor Settings
Theme
Key bindings
Full width
Lines