/**
   * @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;
  }
Example #2
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;
  }
 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 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;
 }
  /**
   * 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);
    }
  }
  int find(int child) {
    if (!contains(child)) {
      throw new RuntimeException();
    }

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

    return child;
  }
Example #7
0
  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));
  }
Example #8
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 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));
 }
Example #10
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];
  }
 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;
 }
Example #12
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;
  }
Example #13
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;    
 }    
Example #14
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;
 }
Example #15
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());
 }
Example #16
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;
  }
  public static void main(String[] args) {
    HashMap hashMap = new HashMap();

    for (int i = 1; i < 130; i++) {
      hashMap.put("abcd" + i, i);
    }

    for (int i = 1; i < 130; i++) {
      System.out.println(hashMap.get("abcd" + i));
    }
    hashMap.put(
        "Lorem ipsum dolor sit amet", "Lorem ipsum dolor sit amet, consectetur adipiscing elit.");

    hashMap.put(
        "In eget lacus rhoncus", "In eget lacus rhoncus, facilisis justo ac, venenatis turpis.");
    hashMap.put(
        "Vestibulum aliquet",
        "Vestibulum aliquet leo sed tellus faucibus, quis feugiat felis lobortis.");
    hashMap.put("Nunc ut augue sit", "Nunc ut augue sit amet leo consectetur volutpat.");
    hashMap.put(
        "Praesent fermentum",
        "Praesent fermentum ex quis nunc porta, sit amet ultricies justo ultricies.");

    hashMap.put("Morbi vehicula justo", "Morbi vehicula justo aliquam velit lacinia tristique.");

    hashMap.put(
        "Suspendisse varius",
        "Suspendisse varius orci ullamcorper, porta tellus sed, dignissim diam.");
    hashMap.put(
        "Nunc fermentum arcu", "Nunc fermentum arcu viverra, porta nibh eget, luctus quam.");
    hashMap.put(
        "Nam finibus felis non",
        "Nam finibus felis non magna scelerisque, eget fringilla nulla scelerisque.");
    hashMap.put("Donec sagittis eros", "Donec sagittis eros quis dui auctor porta.");

    System.out.println(hashMap.get("Lorem ipsum dolor sit amet"));

    hashMap.remove("Morbi vehicula justo");

    System.out.println(hashMap.get("Morbi vehicula justo"));
  }
  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;
  }
Example #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);
  }
 private void dfs(
     List<String> result, String digits, HashMap<String, String> map, int index, String temp) {
   if (index == digits.length()) {
     result.add(temp);
     return;
   }
   String crtDigit = digits.charAt(index) + "";
   String crtChar = map.get(crtDigit);
   for (int i = 0; i < crtChar.length(); i++) {
     char c = crtChar.charAt(i);
     dfs(result, digits, map, index + 1, temp + c);
   }
 }
Example #21
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;
  }
Example #22
0
  public int[] intersect(int[] nums1, int[] nums2) {
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    List<Integer> intersect = new ArrayList<>();
    for (int i : nums1) {
      if (!map.containsKey(i)) {
        map.put(i, 1);
      } else {
        map.put(i, map.get(i) + 1);
      }
    }
    for (int i : nums2) {
      if (map.containsKey(i) && map.get(i) > 0) {
        intersect.add(i);
        map.put(i, map.get(i) - 1);
      }
    }

    int[] result = new int[intersect.size()];
    int i = 0;
    for (Integer num : intersect) {
      result[i++] = num;
    }
    return result;
  }
 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;
 }
Example #24
0
  public boolean check(String s1, String s2) {
    if (s1.equals(s2)) return true;
    if (s1.length() == 1) return false;

    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    for (int i = 0; i < s1.length(); i++) {
      char c = s1.charAt(i);
      if (map.containsKey(c)) map.put(c, map.get(c) + 1);
      else map.put(c, 1);
    }
    for (int i = 0; i < s2.length(); i++) {
      char c = s2.charAt(i);
      if (map.containsKey(c)) map.put(c, map.get(c) - 1);
      else return false;
    }
    for (Map.Entry<Character, Integer> entry : map.entrySet()) {
      int val = entry.getValue().intValue();
      if (val != 0) return false;
    }

    for (int i = 1; i < s1.length(); i++) {
      String left_s1 = s1.substring(0, i);
      String right_s1 = s1.substring(i);
      String left_s2 = s2.substring(0, i);
      String right_s2 = s2.substring(i);
      if (check(left_s1, left_s2) && check(right_s1, right_s2)) return true;
    }
    for (int i = 1; i < s1.length(); i++) {
      String left_s1 = s1.substring(0, i);
      String right_s1 = s1.substring(i);
      String left_s2 = s2.substring(0, s1.length() - i);
      String right_s2 = s2.substring(s1.length() - i);
      if (check(left_s1, right_s2) && check(right_s1, left_s2)) return true;
    }
    return false;
  }
Example #25
0
 // getPackageInfo()
 public PackageInfo getPackageInfo(String packageName, int flags) {
   PackageParser.Package p = mPackages.get(packageName);
   generatePackageInfo(p, flags);
   // PackageInfo generatePackageInfo(PackageParser.Package p, int flags)
   {
     // Everything is already preinstalled in PackageParser.Package
     PackageParser.generatePackageInfo(p, null, flags, 0, 0);
     // frameworks/base/core/java/android/content/pm/PackageParser.java
     // public static PackageInfo generatePackageInfo(PackageParser.Package p,
     //      int gids[], int flags, long firstInstallTime, long lastUpdateTime)
     {
       PackageInfo pi = new PackageInfo();
       pi.signatures = new Signature[N];
       System.arraycopy(p.mSignatures, 0, pi.signatures, 0, N);
     } // PackageParser.generatePackageInfo()
   } // getPackageInfo()
 } // PackageManagerService.getPackageInfo()
  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 String convertToTitle(int n) {
    List<Integer> tmplist = new ArrayList<Integer>();
    HashMap<Integer, String> transform = new HashMap<Integer, String>();
    transform.put(1, "A");
    transform.put(2, "B");
    transform.put(3, "C");
    transform.put(4, "D");
    transform.put(5, "E");
    transform.put(6, "F");
    transform.put(7, "G");
    transform.put(8, "H");
    transform.put(9, "I");
    transform.put(10, "J");
    transform.put(11, "K");
    transform.put(12, "L");
    transform.put(13, "M");
    transform.put(14, "N");
    transform.put(15, "O");
    transform.put(16, "P");
    transform.put(17, "Q");
    transform.put(18, "R");
    transform.put(19, "S");
    transform.put(20, "T");
    transform.put(21, "U");
    transform.put(22, "V");
    transform.put(23, "W");
    transform.put(24, "X");
    transform.put(25, "Y");
    transform.put(0, "Z");

    while (n != 0) {
      int last = n % 26;
      tmplist.add(last);
      if (last == 0) n -= 26;
      n = n / 26;
    }

    StringBuilder sb = new StringBuilder();
    for (int i = tmplist.size() - 1; i >= 0; i--) {
      sb.append(transform.get(tmplist.get(i)));
    }

    return sb.toString();
  }
  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;
  }
  public boolean containsNearbyDuplicate(int[] nums, int k) {
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    int min = Integer.MAX_VALUE;

    for (int i = 0; i < nums.length; i++) {
      if (map.containsKey(nums[i])) {
        int preIndex = map.get(nums[i]);
        int gap = i - preIndex;
        min = Math.min(min, gap);
      }
      map.put(nums[i], i);
    }

    if (min <= k) {
      return true;
    } else {
      return false;
    }
  }
Example #30
0
 // @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++;
     }
   }
 }