Пример #1
0
  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;
  }
Пример #2
0
  /**
   * @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;
  }
Пример #3
0
  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 void setButtonDefs() {
    // Preconditions: words is initialized, preloaded is initialized.
    // Postconditions: definitions of words are added onto the radio buttons.
    // Sets the buttons to be set to random definitions from the preloaded list.
    // Making sure to not load the same definitions.
    Random rnd = new Random();
    HashMap duplicates = new HashMap(5);
    String[] defs = new String[4];

    // Mastery Factor: Implementing an ADT
    // Uses a Hash Map to check for duplicates amongst the options.

    duplicates.add(words[current].getDefinition());
    for (int i = 0; i < 4; i++) {
      String def = preload[rnd.nextInt(PRELOADEDWORDS)].getDefinition();
      while (duplicates.contains(def)) {
        def = preload[rnd.nextInt(PRELOADEDWORDS)].getDefinition();
      }
      duplicates.add(def);
      defs[i] = def;
    }
    aRadBtn.setText(defs[0]);
    bRadBtn.setText(defs[1]);
    cRadBtn.setText(defs[2]);
    dRadBtn.setText(defs[3]);
  }
 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;
 }
Пример #6
0
  /**
   * 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<>();
  }
Пример #7
0
 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;    
 }    
Пример #8
0
  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;
 }
Пример #10
0
 // @return an integer
 public int get(int key) {
   // write your code here
   if (!hash.containsKey(key)) return -1;
   ListNode cur = hash.get(key);
   delete(cur);
   add(cur);
   return cur.val;
 }
Пример #11
0
 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());
 }
Пример #12
0
  /**
   * Sets this <code>XmlReaderContentHandler</code> object's <code>tag</code> field if the given
   * name is the key for a tag and this object's state is not <code>INITIAL</code>. The field is set
   * to the constant that corresponds to the given element name. If the state is <code>INITIAL
   * </code>, the state is set to the given name, which will be one of the sections <code>PROPERTIES
   * </code>, <code>METADATA</code>, or <code>DATA</code>. In either case, this method puts this
   * document handler in the proper state for calling the method <code>endElement</code>.
   *
   * <p>If the state is <code>DATA</code> and the tag is <code>RowTag</code>, <code>DelTag</code>,
   * or <code>InsTag</code>, this method moves the rowset's cursor to the insert row and sets this
   * <code>XmlReaderContentHandler</code> object's <code>idx</code> field to <code>0</code> so that
   * it will be in the proper state when the parser calls the method <code>endElement</code>.
   *
   * @param lName the name of the element; either (1) one of the array elements in the fields <code>
   *     properties</code>, <code>colDef</code>, or <code>data</code> or (2) one of the <code>RowSet
   *     </code> elements <code>"properties"</code>, <code>"metadata"</code>, or <code>"data"</code>
   * @param attributes <code>org.xml.sax.AttributeList</code> objects that are attributes of the
   *     named section element; may be <code>null</code> if there are no attributes, which is the
   *     case for <code>WebRowSet</code> objects
   * @exception SAXException if a general SAX error occurs
   */
  public void startElement(String uri, String lName, String qName, Attributes attributes)
      throws SAXException {
    int tag;
    String name = "";

    name = lName;

    switch (getState()) {
      case PROPERTIES:
        tempCommand = "";
        tag = propMap.get(name);
        if (tag == PropNullTag) setNullValue(true);
        else setTag(tag);
        break;
      case METADATA:
        tag = colDefMap.get(name);

        if (tag == MetaNullTag) setNullValue(true);
        else setTag(tag);
        break;
      case DATA:

        /**
         * This has been added to clear out the values of the previous read so that we should not
         * add up values of data between different tags
         */
        tempStr = "";
        tempUpdate = "";
        if (dataMap.get(name) == null) {
          tag = NullTag;
        } else if (dataMap.get(name) == EmptyStringTag) {
          tag = EmptyStringTag;
        } else {
          tag = dataMap.get(name);
        }

        if (tag == NullTag) {
          setNullValue(true);
        } else if (tag == EmptyStringTag) {
          setEmptyStringValue(true);
        } else {
          setTag(tag);

          if (tag == RowTag || tag == DelTag || tag == InsTag) {
            idx = 0;
            try {
              rs.moveToInsertRow();
            } catch (SQLException ex) {;
            }
          }
        }

        break;
      default:
        setState(name);
    }
  }
Пример #13
0
  /**
   * @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;
  }
  int find(int child) {
    if (!contains(child)) {
      throw new RuntimeException();
    }

    while (child != rec.get(child)) {
      child = rec.get(child);
    }

    return child;
  }
 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;
 }
Пример #16
0
  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;
  }
Пример #17
0
 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;
 }
  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;
  }
Пример #19
0
  /**
   * 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);
  }
Пример #20
0
  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;
  }
Пример #21
0
  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];
  }
Пример #22
0
  /**
   * Save the state of this <tt>HashSet</tt> instance to a stream (that is, serialize this set).
   *
   * @serialData The capacity of the backing <tt>HashMap</tt> instance (int), and its load factor
   *     (float) are emitted, followed by the size of the set (the number of elements it contains)
   *     (int), followed by all of its elements (each an Object) in no particular order.
   */
  private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
    // Write out any hidden serialization magic
    s.defaultWriteObject();

    // Write out HashMap capacity and load factor
    s.writeInt(map.capacity());
    s.writeFloat(map.loadFactor());

    // Write out size
    s.writeInt(map.size());

    // Write out all elements in the proper order.
    for (Iterator i = map.keySet().iterator(); i.hasNext(); ) s.writeObject(i.next());
  }
Пример #23
0
 public boolean isIsomorphic(String s, String t) {
   HashMap<Character, Character> map = new HashMap<>();
   for (int i = 0; i < s.length(); i++) {
     if (map.containsKey(s.charAt(i))) {
       if (t.charAt(i) == map.get(s.charAt(i))) continue;
       else {
         return false;
       }
     } else if (map.containsValue(t.charAt(i))) {
       return false;
     }
     map.put(s.charAt(i), t.charAt(i));
   }
   return true;
 }
Пример #24
0
  @SuppressWarnings({"unchecked", "rawtypes", "unused"})
  @Override
  public V put(K key, V value) {
    K k = (K) maskNull(key);
    int h = HashMap.hash(k.hashCode());
    Entry[] tab = getTable();
    int i = indexFor(h, tab.length);

    for (Entry<K, V> e = tab[i]; e != null; e = e.next) {
      if (h == e.hash && eq(k, e.get())) {
        V oldValue = e.value;
        if (value != oldValue) {
          e.value = value;
        }
        return oldValue;
      }
    }

    modCount++;
    Entry<K, V> e = tab[i];
    //		tab[i] = new Entry<K,V>(k, value, queue, h, e);
    if (++size >= threshold) {
      resize(tab.length * 2);
    }
    return null;
  }
Пример #25
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  @Override
  public V remove(Object key) {
    Object k = maskNull(key);
    int h = HashMap.hash(k.hashCode());
    Entry[] tab = getTable();
    int i = indexFor(h, tab.length);

    Entry<K, V> prev = tab[i];
    Entry<K, V> e = prev;

    while (e != null) {
      Entry<K, V> next = e.next;
      if (h == e.hash && eq(k, e.get())) {
        modCount++;
        size--;
        if (prev == e) {
          tab[i] = next;
        } else {
          prev.next = next;
        }
        return e.value;
      }
      prev = e;
      e = next;
    }
    return null;
  }
Пример #26
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  Entry<K, V> removeMapping(Object o) {
    if (!(o instanceof Map.Entry)) {
      return null;
    }
    Entry[] tab = getTable();
    Map.Entry entry = (Map.Entry) o;
    Object k = maskNull(entry.getKey());
    int h = HashMap.hash(k.hashCode());
    int i = indexFor(h, tab.length);

    Entry<K, V> prev = tab[i];
    Entry<K, V> e = prev;

    while (e != null) {
      Entry<K, V> next = e.next;
      if (h == e.hash && e.equals(entry)) {
        modCount++;
        size--;
        if (prev == e) {
          tab[i] = next;
        } else {
          prev.next = next;
        }
        return e;
      }
      prev = e;
      e = next;
    }

    return null;
  }
Пример #27
0
  /**
   * 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);
        }
      }
    }
  }
Пример #28
0
 HashMap<Character, Integer> part(int idx) {
   if (idx < left.size()) {
     return left;
   } else {
     return right;
   }
 }
Пример #29
0
  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;
  }
Пример #30
0
  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;
  }