문제로
풀이 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { fun twoSum(nums: IntArray, target: Int): IntArray { val map = mutableMapOf<Int, Int>() for(i in 0 until nums.size) { // for(i in nums.indices) { val cur:Int = nums[i] val sub:Int = target - cur if(map.containsKey(sub)){ return intArrayOf(map.get(sub)!!, i) } else { map.put(cur, i) } } return intArrayOf() } } *HashMap의 get의 시간복잡도가 O(1) 이라길래 코드를 까봤다...* ## get은?👇 ```kotlin /** * Returns the value to which the specified key is mapped, or {null} if this map contains no mapping for the key. * More formally, if this map contains a mapping from a key {k} to a value {v} such that {(key==null ? knull : key.squals(k))}, then this method returns {v}; otherwise it returns {null}. (There can be at most one such mapping.) * A return valsue of {null} does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to {null}. the {containsKey} operation may be used to distinguish these two cases. */ public V get(Object key) { Node e; return (e = getNode(key)) == null ? null : e.value; } ``` 주석 google 번역 /** * 지정된 키가 매핑된 값을 반환하거나, 이 맵에 키에 대한 매핑이 포함되어 있지 않으면 **null**을 반환합니다. * 보다 공식적으로, 이 맵에 **(key==null ? knull : key.squals(k))**와 같이 키 **k**에서 값 **v**로의 매핑이 포함되어 있는 경우 이 메서드는 **v**를 반환합니다. 그렇지 않으면 **null**을 반환합니다. (이러한 매핑은 최대 하나만 있을 수 있습니다.) * 반환 값 **null**이 반드시 맵에 키에 대한 매핑이 포함되어 있지 않음을 나타내는 것은 아닙니다. 맵이 명시적으로 키를 **null**에 매핑하는 것도 가능합니다. **containsKey** 작업을 사용하여 이 두 가지 경우를 구별할 수 있습니다. */ get의 실체, getNode는?👇 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 /** * Implements Map.get and releted methos. * 매개변수: {key} - the key * 반환: the node, or null if none */ final Node<K,V> getNode(Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & (hash = hash(key))]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; } Node는? 1 2 3 4 5 6 7 static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; ... } 👉 Node는 key-value 하나를 담는 객체
...