/** * Creates and initializes three new <code>HashMap</code> objects that map the strings returned by * the SAX parser to <code>Integer</code> objects. The strings returned by the parser will match * the strings that are array elements in this <code>XmlReaderContentHandler</code> object's * <code>properties</code>, <code>colDef</code>, or <code>data</code> fields. For each array * element in these fields, there is a corresponding constant defined. It is to these constants * that the strings are mapped. In the <code>HashMap</code> objects, the string is the key, and * the integer is the value. * * <p>The purpose of the mapping is to make comparisons faster. Because comparing numbers is more * efficient than comparing strings, the strings returned by the parser are mapped to integers, * which can then be used in a <code>switch</code> statement. */ private void initMaps() { int items, i; propMap = new HashMap<>(); items = properties.length; for (i = 0; i < items; i++) { propMap.put(properties[i], Integer.valueOf(i)); } colDefMap = new HashMap<>(); items = colDef.length; for (i = 0; i < items; i++) { colDefMap.put(colDef[i], Integer.valueOf(i)); } dataMap = new HashMap<>(); items = data.length; for (i = 0; i < items; i++) { dataMap.put(data[i], Integer.valueOf(i)); } // Initialize connection map here typeMap = new HashMap<>(); }
public boolean canPermutePalindrome(String s) { // Time: O(n), Space: O(n) if (s == null || s.length() == 0) { return true; } HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (!map.containsKey(c)) { map.put(c, 1); } else { map.put(c, map.get(c) + 1); } } boolean single = false; for (Integer i : map.values()) { if (i % 2 == 1) { if (single) { return false; } single = true; } } return true; }
/** * @param k: The number k. * @return: The kth prime number as description. */ public long kthPrimeNumber(int k) { PriorityQueue<Long> queue = new PriorityQueue<Long>(); HashMap<Long, Boolean> map = new HashMap<Long, Boolean>(); Long[] Primes = new Long[3]; Primes[0] = Long.valueOf(3); Primes[1] = Long.valueOf(5); Primes[2] = Long.valueOf(7); for (int i = 0; i < Primes.length; ++i) { queue.add(Primes[i]); map.put(Primes[i], true); } Long number = Primes[0]; for (int i = 1; i <= k; ++i) { number = queue.poll(); for (int j = 0; j < Primes.length; ++j) { if (map.containsKey(number * Primes[j])) { continue; } else { map.put(number * Primes[j], true); queue.add(number * Primes[j]); } } } return number; }
/** * @param nums1 an integer array * @param nums2 an integer array * @return an integer array */ public int[] intersection(int[] nums1, int[] nums2) { // Write your code here if (nums1 == null || nums2 == null) return null; HashMap<Integer, Integer> map = new HashMap(); for (int i = 0; i < nums1.length; i++) { if (map.get(nums1[i]) != null) { map.put(nums1[i], map.get(nums1[i]) + 1); } else { map.put(nums1[i], 1); } } ArrayList<Integer> list = new ArrayList(); for (int j = 0; j < nums2.length; j++) { if (map.containsKey(nums2[j]) && map.get(nums2[j]) > 0) { list.add(nums2[j]); map.put(nums2[j], map.get(nums2[j]) - 1); } } int[] result = new int[list.size()]; for (int k = 0; k < list.size(); k++) { result[k] = list.get(k); } return result; }
public int romanToInt(String s) { // create hashmap for roman numeral HashMap<Character, Integer> map = new HashMap<Character, Integer>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); // convert string to array int[] intArr = new int[s.length()]; char roman; for (int i = 0; i < s.length(); i++) { intArr[i] = map.get(s.charAt(i)); } int result = 0; if (intArr.length == 1) { return map.get(s.charAt(0)); } else { for (int i = 0; i < (intArr.length - 1); i++) { if (intArr[i] >= intArr[i + 1]) { result += intArr[i]; } else { result -= intArr[i]; } } result += intArr[s.length() - 1]; } return result; }
public static void main(String[] args) { HashMap hm = new HashMap(); hm.put(1, 20); hm.put(2, 30); hm.put(5, 50); System.out.println("Value for the Key 1: " + hm.get(1)); System.out.println("Value for the Key 5: " + hm.get(5)); System.out.println("Size : " + hm.size()); }
public static void main(String[] args) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(1, 90); map.put(2, 95); map.put(17, 85); System.out.println(map.get(1)); System.out.println(map.get(2)); System.out.println(map.get(17)); System.out.println(map.get(null)); }
public static void main(String[] args) { // TODO Auto-generated method stub HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(5); map.put(1, 10); map.put(2, 20); map.put(3, 30); map.put(4, 40); map.put(5, 50); map.put(6, 60); System.out.println(map.get(5)); map.remove(5); System.out.println(map.get(5)); }
public String minWindow(String s, String t) { if (s.length() == 0 || t.length() > s.length()) return ""; HashMap<Character, Integer> target = new HashMap<Character, Integer>(); char[] tArr = t.toCharArray(); for (char one : tArr) { if (!target.containsKey(one)) target.put(one, 1); else target.put(one, target.get(one) + 1); } int len = s.length() + 1; String res = ""; int pos = 0; int prev = 0; int count = 0; HashMap<Character, Integer> m = new HashMap<Character, Integer>(); while (pos < s.length()) { char oneChar = s.charAt(pos); if (target.containsKey(oneChar)) { if (!m.containsKey(oneChar)) { count++; m.put(oneChar, 1); } else { m.put(oneChar, m.get(oneChar) + 1); if (m.get(oneChar) <= target.get(oneChar)) count++; } } // move the prev to update len if (count == t.length()) { while (prev <= pos) { char temp = s.charAt(prev); if (!m.containsKey(temp)) prev++; else if (m.get(temp) > target.get(temp)) { prev++; m.put(temp, m.get(temp) - 1); } else { if (pos - prev + 1 < len) { len = pos - prev + 1; res = s.substring(prev, pos + 1); } break; } } } pos++; } return res; }
public int[] twoSum_hashmap(int[] numbers, int target) { if (numbers == null || numbers.length < 2) { return null; } HashMap<Integer, Integer> hs = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; i++) { hs.put(numbers[i], i + 1); } int[] a = new int[2]; for (int i = 0; i < numbers.length; i++) { if (hs.containsKey(target - numbers[i])) { // the complexity for containsKey is basically O(1) int index1 = i + 1; int index2 = hs.get(target - numbers[i]); if (index1 == index2) { continue; } a[0] = index1; a[1] = index2; return a; } } return a; }
public RandomListNode copyRandomList(RandomListNode head) { RandomListNode result = new RandomListNode(-1); RandomListNode R = result; HashMap<RandomListNode,List<RandomListNode>> map = new HashMap<RandomListNode,List<RandomListNode>>(); HashMap<RandomListNode,RandomListNode> mapNode = new HashMap<RandomListNode,RandomListNode>(); while(head!=null){ //copy to result RandomListNode node = new RandomListNode(head.label); result.next = node; result = result.next; //map head node to result node mapNode.put(head,node); //deal random pointer List<RandomListNode> tmpList = map.get(head.random); if(tmpList==null){ tmpList = new ArrayList<RandomListNode>(); map.put(head.random,tmpList); } tmpList.add(node); head = head.next; } for(RandomListNode node:map.keySet()){ List<RandomListNode> tmpList = map.get(node); RandomListNode k = mapNode.get(node); for(RandomListNode n:tmpList){ n.random = k; } } return R.next; }
/** * Precalculo todos los adyacentes de todos los nodos y me armo el grafo para luego aplicar el * algoritmo que resuelve el problema * * <p>Pre: (valoresNodos tiene dimension n*n con n natural > 0) && (0<=powerUpInicial) && * (valoresNodos[i][j] = valorNodoIJ) && (nodoInicial y nodoDestino tienen coord validas) * * @param valoresNodos * @param powerUpInicial */ public Juego( int[][] valoresNodos, int powerUpInicial, int filaInicial, int columnaInicial, int filaDestino, int columnaDestino) { // inicializo estructuras y atributos this.nodoInicial = new Nodo(filaInicial, columnaInicial, powerUpInicial); this.nodoDestino = new Nodo( filaDestino, columnaDestino, 0 /*dummy level l, l puede ser cualquiera entre [0..powerUpInicial]*/); this.graph = new HashMap<Nodo, NodoMetadata>(); // genero el grafo que modela el problema int dimension = valoresNodos.length; for (int level = powerUpInicial; level >= 0; level--) { for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { Nodo nodo = new Nodo(i, j, level); // de nuevo fix para complejidad, no tiene sentido una potencia instrinseca mayor a dim // nunca va a saltar mas alla de los limites de la matriz int nodoValue = (valoresNodos[i][j] < dimension) ? valoresNodos[i][j] : dimension; boolean fueVisitado = false; List<Nodo> alcanzables = calcularAlcanzables(nodo, nodoValue, dimension); NodoMetadata metaData = new NodoMetadata(nodoValue, fueVisitado, alcanzables, null); graph.put(nodo, metaData); } } } }
public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> list = new ArrayList<Integer>(); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); quickSort(nums, 0, nums.length - 1); for (int i = 0; i < nums.length; i++) { if (i > 0 && nums[i] == nums[i - 1]) continue; int target = 0 - nums[i]; for (int j = i + 1; j < nums.length; j++) { int diff = target - nums[j]; if (map.containsKey(diff)) { list.add(nums[i]); list.add(diff); list.add(nums[j]); res.add(list); list = new ArrayList<Integer>(); } map.put(nums[j], j); } map.clear(); } return res; }
public List<Integer> findSubstring(String s, String[] words) { List<Integer> res = new ArrayList<Integer>(); int wlength = words.length; if (wlength == 0) return res; int size = words[0].length(); int slength = s.length(); if (wlength * size > slength) return res; HashMap<String, Integer> wordHashMap = new HashMap<String, Integer>(); for (int i = 0; i < wlength; i++) wordHashMap.put( words[i], !wordHashMap.containsKey(words[i]) ? 1 : wordHashMap.get(words[i]) + 1); for (int i = 0; i < slength - size * wlength + 1; i++) { HashMap<String, Integer> tempHashMap = new HashMap<String, Integer>(wordHashMap); for (int j = 0; j < wlength; j++) { String subString = s.substring(i + j * size, i + (j + 1) * size); if (tempHashMap.containsKey(subString)) { int count = tempHashMap.get(subString); if (count == 1) tempHashMap.remove(subString); else tempHashMap.replace(subString, count - 1); } else { break; } } if (tempHashMap.isEmpty()) res.add(i); } return res; }
public boolean containsDuplicate(int[] nums) { HashMap<Integer, String> myMap = new HashMap<Integer, String>(); for (int n : nums) { if (myMap.put(n, "a") != null) return true; } return false; }
public int merge(HashMap<Integer, Integer> map, int left, int right) { int upper = right + map.get(right) - 1; int lower = left - map.get(left) + 1; int len = upper - lower + 1; map.put(upper, len); map.put(lower, len); return len; }
public List<Integer> findRepeatedDnaSequences(String s) { List<Integer> list = new ArrayList(); HashMap<Integer, Integer> map = new HashMap(); int key = 0; for (int i = 0; i < s.length(); i++) { key = ((key << 3) | (s.charAt(i) & 0x7)) & 0x3fffffff; if (i < 9) continue; if (map.get(key) == null) map.put(key, 1); else if (map.get(key) == 1) { list.add(s.substring(i - 9, i + 1)); map.put(key, 2); } } return list; }
public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if (root == null) { return res; } // map's key is column, we assume the root column is zero, the left node wi ll minus 1 ,and the // right node will plus 1 HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(); Queue<TreeNode> queue = new LinkedList<>(); // use a HashMap to store the TreeNode and the according cloumn value HashMap<TreeNode, Integer> weight = new HashMap<TreeNode, Integer>(); queue.offer(root); weight.put(root, 0); int min = 0; // when output the arraylist from map, need to start with min. while (!queue.isEmpty()) { TreeNode node = queue.poll(); int w = weight.get(node); if (!map.containsKey(w)) { map.put(w, new ArrayList<>()); } map.get(w).add(node.val); if (node.left != null) { queue.add(node.left); weight.put(node.left, w - 1); } if (node.right != null) { queue.add(node.right); weight.put(node.right, w + 1); } // update min ,min means the minimum column value, which is the left most node min = Math.min(min, w); } while (map.containsKey(min)) { res.add(map.get(min++)); } return res; }
// @param key, an integer // @param value, an integer // @return nothing public void set(int key, int value) { // write your code here if (hash.containsKey(key)) { hash.get(key).val = value; get(key); } else { ListNode cur = new ListNode(key, value); if (len == capacity) { ListNode temp = head.next; delete(temp); hash.remove(temp.key); hash.put(key, cur); add(cur); } else { add(cur); hash.put(key, cur); len++; } } }
public boolean add(Object key, Object value) { int lookup = getLookup(key, key.hashCode()); if (lookup >= 0) { return false; } super.put(key, value); return true; }
public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i])) { int preIndex = map.get(nums[i]); if (i - preIndex <= k) return true; } map.put(nums[i], i); } return false; }
public int longestConsecutive(int[] num) { if (null == num || 0 == num.length) return 0; int max = 1; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i : num) { if (map.containsKey(i)) continue; map.put(i, 1); if (map.containsKey(i - 1)) max = Math.max(max, merge(map, i - 1, i)); if (map.containsKey(i + 1)) max = Math.max(max, merge(map, i, i + 1)); } return max; }
/** * Stores a bitmap for use by a game tile in a level. * * @param int resourceId - The bitmap resource ID. * @return Bitmap - The Bitmap instance for the given resource ID. */ private Bitmap setAndGetGameTileBitmap(int resourceId) { if (!mGameTileBitmaps.containsKey(resourceId)) { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeResource(mGameContext.getResources(), resourceId); if (bitmap != null) { mGameTileBitmaps.put(resourceId, bitmap); } } return mGameTileBitmaps.get(resourceId); }
public boolean set(int index, Object key, Object value) throws IndexOutOfBoundsException { checkRange(index); if (keySet().contains(key) && getIndex(key) != index) { return false; } super.remove(objectKeyTable[index]); super.put(key, value); return true; }
public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> numbers = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (numbers.get(target - nums[i]) != null) { int[] res = {numbers.get(target - nums[i]) + 1, i + 1}; return res; } else { numbers.put(nums[i], i); } } int[] res = {0, 0}; return res; }
void union(int child1, int child2) { if (!contains(child1) || !contains(child2)) { return; } int parent1 = find(child1); int parent2 = find(child2); if (parent1 != parent2) { rec.put(parent1, parent2); count--; } }
public int maxPoints(Point[] points) { if (points == null || points.length == 0) { return 0; } HashMap<Double, Integer> map = new HashMap<>(); int res = 0; for (int i = 0; i < points.length; i++) { int vertical = 0; int dup = 1; for (int j = i + 1; j < points.length; j++) { if (points[i].x == points[j].x) { if (points[i].y == points[j].y) { dup++; } else { vertical++; } } else { double slope; if (points[j].y == points[i].y) { slope = 0.0; } else { slope = (1.0) * (points[j].y - points[i].y) / (points[j].x - points[i].x); } if (!map.containsKey(slope)) { map.put(slope, 1); } else { map.put(slope, map.get(slope) + 1); } } } for (Integer val : map.values()) { res = Math.max(res, dup + val); } res = Math.max(res, dup + vertical); map.clear(); } return res; }
public int singleNumber_On(int[] A) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int i; for (i = 0; i < A.length; i++) { map.put(A[i], map.containsKey(A[i]) ? map.get(A[i]) + 1 : 1); } for (i = 0; i < A.length; i++) { if (map.get(A[i]) != 3) { break; } } return A[i]; }
/** * @Method: getMenuAdapter @Description: ���� popupwindow ������ * * @param menuNameArray * @param menuImageArray * @return */ private ListAdapter getMenuAdapter(String[] menuNameArray, int[] menuImageArray) { ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); // ѭ�� ���������ӦͼƬ����HashMap for (int i = 0; i < menuNameArray.length; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("itemImage", menuImageArray[i]); map.put("itemText", menuNameArray[i]); data.add(map); } // ���������� SimpleAdapter simperAdapter = new SimpleAdapter( this, data, R.layout.item_menu, new String[] {"itemImage", "itemText"}, new int[] {R.id.item_image, R.id.item_text}); // ����һ�������� return simperAdapter; }
public int lengthOfLongestSubstring(String s) { if (s.length() == 0) return 0; HashMap<Character, Integer> map = new HashMap<>(); int max = 0; for (int i = 0, j = 0; i < s.length(); i++) { if (map.containsKey(s.charAt(i))) { j = Math.max(j, map.get(s.charAt(i)) + 1); } map.put(s.charAt(i), i); max = Math.max(max, i - j + 1); } return max; }