public List<List<String>> groupAnagrams(String[] strs) {
    List<List<String>> rst = new ArrayList<List<String>>();
    if (strs == null) {
      return rst;
    }

    List<String> order = new ArrayList<String>();
    HashMap<String, List<String>> map = new HashMap<String, List<String>>();
    for (String str : strs) {
      char[] arr = str.toCharArray();
      Arrays.sort(arr);
      String s = new String(arr);
      if (!map.containsKey(s)) {
        List<String> l = new ArrayList<String>();
        l.add(str);
        order.add(s);
        map.put(s, l);
      } else {
        map.get(s).add(str);
      }
    }
    Collections.sort(order);
    for (String str : order) {
      Collections.sort(map.get(str));
      rst.add(map.get(str));
    }
    return rst;
  }
Example #2
0
  /**
   * Returns a list of all active and finished one-time orders going back n number of months, for
   * all direct immediate of the given parent user id. This is useful for determining usage across
   * all child users.
   *
   * @param parentUserId parent user id
   * @param itemId item id of order lines
   * @param months previous number of months to include (1 = 1 month period starting from today)
   * @return list of found one-time orders, empty list if none found
   */
  @SuppressWarnings("unchecked")
  public List<OrderLineDTO> findOnetimeByParentUserItem(
      Integer parentUserId, Integer itemId, Integer months) {
    UserDTO parent = new UserBL(parentUserId).getEntity();
    if (parent == null || parent.getCustomer() == null) {
      LOG.warn("Parent user " + parentUserId + " does not exist or is not a customer!");
      return Collections.emptyList();
    }

    final String hql =
        "select line "
            + " from OrderLineDTO line "
            + " where line.deleted = 0 "
            + "  and line.item.id = :itemId "
            + "  and line.purchaseOrder.baseUserByUserId.customer.parent.id = :parentId"
            + "  and line.purchaseOrder.orderPeriod.id = :period "
            + "  and (line.purchaseOrder.orderStatus.orderStatusFlag = :active_status"
            + "       or line.purchaseOrder.orderStatus.orderStatusFlag = :finished_status)"
            + "  and line.purchaseOrder.deleted = 0 "
            + "  and line.purchaseOrder.createDate > :startdate ";

    Query query = getSession().createQuery(hql);
    query.setParameter("itemId", itemId);
    query.setParameter("parentId", parent.getCustomer().getId());
    query.setParameter("period", Constants.ORDER_PERIOD_ONCE);
    query.setParameter("active_status", OrderStatusFlag.INVOICE.ordinal());
    query.setParameter("finished_status", OrderStatusFlag.FINISHED);

    DateMidnight startdate = new DateMidnight().minusMonths(months);
    query.setParameter("startdate", startdate.toDate());

    return query.list();
  }
  public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
    // Start typing your Java solution below
    // DO NOT write main() function

    ArrayList<Interval> res = new ArrayList<Interval>();
    if (intervals.size() == 0) return res;
    Collections.sort(intervals, new MyC());
    int start = 0;
    int end = 0;
    for (int i = 0; i < intervals.size(); i++) {
      if (i == 0) {
        start = intervals.get(i).start;
        end = intervals.get(i).end;
      } else {
        if (intervals.get(i).start <= end) {
          end = Math.max(end, intervals.get(i).end);
        } else {
          res.add(new Interval(start, end));
          start = intervals.get(i).start;
          end = intervals.get(i).end;
        }
      }
    }
    res.add(new Interval(start, end));
    return res;
  }
  public void bfs(
      UndirectedGraphNode node,
      Map<UndirectedGraphNode, Boolean> visited,
      List<List<Integer>> result) { // BFS+queue

    List<Integer> row = new ArrayList<>();

    Queue<UndirectedGraphNode> queue = new LinkedList<>(); // 这个的写法 是神马意思啊  左边是队列右边是linkedlist = =
    visited.put(node, true);
    queue.offer(node);

    while (!queue.isEmpty()) {
      UndirectedGraphNode u = queue.poll();
      row.add(u.label);

      for (UndirectedGraphNode v : u.neighbors) {
        if (visited.get(v) == false) {
          visited.put(v, true);
          queue.offer(v);
        }
      }
    }

    Collections.sort(row);
    result.add(row);
  }
Example #5
0
  public List<int[]> getSkyline(int[][] buildings) {
    if (buildings == null || buildings.length == 0) {
      return Collections.emptyList();
    }

    final PriorityQueue<Building> endings =
        new PriorityQueue<>((v1, v2) -> Integer.compare(v1.to, v2.to));
    final PriorityQueue<Integer> heights = new PriorityQueue<>((v1, v2) -> Integer.compare(v2, v1));

    final List<int[]> result = new ArrayList<>();

    // iterate over each of the building
    for (int[] build : buildings) {
      final Building building = new Building(build);

      while (endings.size() > 0 && endings.peek().to < building.from) {
        removeBuildings(endings, heights, result);
      }

      if (heights.size() == 0 || building.height > heights.peek()) {
        result.add(new int[] {building.from, building.height});
      }
      heights.add(building.height);
      endings.add(building);
    }

    while (endings.size() > 0) {
      removeBuildings(endings, heights, result);
    }

    return result;
  }
  public List<ReferenceType> visibleClasses() {
    List<ReferenceType> classes = null;
    try {
      Cache local = (Cache) getCache();

      if (local != null) {
        classes = local.visibleClasses;
      }
      if (classes == null) {
        JDWP.ClassLoaderReference.VisibleClasses.ClassInfo[] jdwpClasses =
            JDWP.ClassLoaderReference.VisibleClasses.process(vm, this).classes;
        classes = new ArrayList<ReferenceType>(jdwpClasses.length);
        for (int i = 0; i < jdwpClasses.length; ++i) {
          classes.add(vm.referenceType(jdwpClasses[i].typeID, jdwpClasses[i].refTypeTag));
        }
        classes = Collections.unmodifiableList(classes);
        if (local != null) {
          local.visibleClasses = classes;
          if ((vm.traceFlags & VirtualMachine.TRACE_OBJREFS) != 0) {
            vm.printTrace(
                description()
                    + " temporarily caching visible classes (count = "
                    + classes.size()
                    + ")");
          }
        }
      }
    } catch (JDWPException exc) {
      throw exc.toJDIException();
    }
    return classes;
  }
 public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
   List<List<Integer>> result = new ArrayList<>();
   if (root == null) {
     return result;
   }
   Queue<TreeNode> queue = new LinkedList<TreeNode>();
   queue.offer(root);
   boolean flagOdd = true;
   while (!queue.isEmpty()) {
     int qsize = queue.size();
     List<Integer> subResult = new ArrayList<Integer>();
     for (int i = 0; i < qsize; i++) {
       TreeNode node = queue.poll();
       subResult.add(node.val);
       if (node.left != null) {
         queue.offer(node.left);
       }
       if (node.right != null) {
         queue.offer(node.right);
       }
     }
     if (flagOdd) {
       result.add(subResult);
     } else {
       Collections.reverse(subResult);
       result.add(subResult);
     }
     flagOdd = !flagOdd;
   }
   return result;
 }
Example #8
0
  private static void sortByLastPushedDateAndName(List<Project> projects) {
    Collections.sort(
        projects,
        new Comparator<Project>() {
          @Override
          public int compare(Project p1, Project p2) {
            int compareLastPushedDate;
            if (p1.lastPushedDate == null && p2.lastPushedDate == null) {
              return p1.name.compareTo(p2.name);
            }

            if (p1.lastPushedDate == null) {
              return 1;
            } else if (p2.lastPushedDate == null) {
              return -1;
            }

            compareLastPushedDate = p2.lastPushedDate.compareTo(p1.lastPushedDate);
            if (compareLastPushedDate == 0) {
              return p1.name.compareTo(p2.name);
            }
            return compareLastPushedDate;
          }
        });
  }
Example #9
0
 public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
   // Start typing your Java solution below
   // DO NOT write main() function
   Collections.sort(
       intervals,
       new Comparator<Interval>() {
         public int compare(Interval a, Interval b) {
           return new Integer(a.start).compareTo(new Integer(b.start));
         }
       });
   ArrayList<Interval> res = new ArrayList<Interval>();
   if (intervals.size() == 0) return res;
   Interval first = new Interval(intervals.get(0).start, intervals.get(0).end);
   if (intervals.size() == 1) {
     res.add(first);
     return res;
   }
   int i = 1;
   while (i < intervals.size()) {
     if (intervals.get(i).start > first.end) {
       res.add(first);
       first = intervals.get(i);
     } else if (intervals.get(i).end > first.end) {
       first.end = intervals.get(i).end;
     }
     i++;
   }
   res.add(first);
   return res;
 }
Example #10
0
 @Override
 public <K2> TreeMap<K2, V> mapKeys(
     Function<? super K, ? extends K2> keyMapper,
     BiFunction<? super V, ? super V, ? extends V> valueMerge) {
   final Comparator<K2> comparator = naturalComparator();
   return Collections.mapKeys(this, TreeMap.<K2, V>empty(comparator), keyMapper, valueMerge);
 }
  public List<Interval> merge(List<Interval> intervals) {
    if (intervals.size() <= 1) return intervals;

    // Sort by ascending starting point using an anonymous Comparator
    Collections.sort(
        intervals,
        new Comparator<Interval>() {
          @Override
          public int compare(Interval i1, Interval i2) {
            return Integer.compare(i1.start, i2.start);
          }
        });

    List<Interval> result = new LinkedList<Interval>();
    int start = intervals.get(0).start;
    int end = intervals.get(0).end;

    for (Interval interval : intervals) {
      if (interval.start <= end) // Overlapping intervals, move the end if needed
      end = Math.max(end, interval.end);
      else { // Disjoint intervals, add the previous one and reset bounds
        result.add(new Interval(start, end));
        start = interval.start;
        end = interval.end;
      }
    }

    // Add the last interval
    result.add(new Interval(start, end));
    return result;
  }
 public List<Integer> findMinHeightTrees(int n, int[][] edges) {
   if (n == 1) return Collections.singletonList(0);
   List<HashSet<Integer>> list = new ArrayList<HashSet<Integer>>(n);
   for (int i = 0; i < n; i++) {
     list.add(new HashSet<Integer>());
   }
   for (int i = 0; i < edges.length; i++) {
     list.get(edges[i][0]).add(edges[i][1]);
     list.get(edges[i][1]).add(edges[i][0]);
   }
   List<Integer> leaves = new ArrayList<Integer>();
   for (int i = 0; i < n; i++) {
     if (list.get(i).size() == 1) {
       leaves.add(i);
     }
   }
   while (n > 2) {
     n -= leaves.size();
     List<Integer> newLeaves = new ArrayList<Integer>();
     for (Integer leaf : leaves) {
       int j = list.get(leaf).iterator().next();
       list.get(j).remove(leaf);
       if (list.get(j).size() == 1) {
         newLeaves.add(j);
       }
     }
     leaves = newLeaves;
   }
   return leaves;
 }
Example #13
0
 public List<List<Integer>> levelOrderBottom(TreeNode root) {
   List<List<Integer>> ret = new ArrayList();
   if (root == null) return ret;
   helper(ret, root, 1);
   Collections.reverse(ret);
   return ret;
 }
Example #14
0
 static {
   Set<EncodingRule> rules = new HashSet<EncodingRule>();
   rules.add(new EncodingRule("*", "%2A"));
   rules.add(new EncodingRule("+", "%20"));
   rules.add(new EncodingRule("%7E", "~"));
   ENCODING_RULES = Collections.unmodifiableSet(rules);
 }
Example #15
0
  /*
   * Returns a keystore entry alias and a list of target keystores.
   * When the supplied alias prefix identifies a keystore then that single
   * keystore is returned. When no alias prefix is supplied then all the
   * keystores are returned.
   */
  private AbstractMap.SimpleEntry<String, Collection<KeyStore>> getKeystoresForReading(
      String alias) {

    String[] splits = alias.split(this.entryNameSeparatorRegEx, 2);
    if (splits.length == 2) { // prefixed alias
      KeyStore keystore = keystores.get(splits[0]);
      if (keystore != null) {
        return new AbstractMap.SimpleEntry<>(
            splits[1], (Collection<KeyStore>) Collections.singleton(keystore));
      }
    } else if (splits.length == 1) { // unprefixed alias
      // Check all keystores for the first occurrence of the alias
      return new AbstractMap.SimpleEntry<>(alias, keystores.values());
    }
    return new AbstractMap.SimpleEntry<>(
        "", (Collection<KeyStore>) Collections.<KeyStore>emptyList());
  }
Example #16
0
 /**
  * Returns a TreeMap containing {@code n} values supplied by a given Supplier {@code s}.
  *
  * @param <K> The key type
  * @param <V> The value type
  * @param keyComparator The comparator used to sort the entries by their key
  * @param n The number of elements in the TreeMap
  * @param s The Supplier computing element values
  * @return A TreeMap of size {@code n}, where each element contains the result supplied by {@code
  *     s}.
  * @throws NullPointerException if {@code keyComparator} or {@code s} are null
  */
 @SuppressWarnings("unchecked")
 public static <K, V> TreeMap<K, V> fill(
     Comparator<? super K> keyComparator,
     int n,
     Supplier<? extends Tuple2<? extends K, ? extends V>> s) {
   Objects.requireNonNull(keyComparator, "keyComparator is null");
   Objects.requireNonNull(s, "s is null");
   return ofEntries(keyComparator, Collections.fill(n, (Supplier<? extends Tuple2<K, V>>) s));
 }
Example #17
0
 public ArrayList<ArrayList<Integer>> subsetsWithDup(ArrayList<Integer> S) {
   // write your code here
   ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
   if (S == null || S.size() == 0) return res;
   ArrayList<Integer> cur = new ArrayList<Integer>();
   Collections.sort(S);
   helper(res, cur, 0, S);
   return res;
 }
Example #18
0
  private static void sortDatum(
      List<Posting> postings,
      List<Issue> issues,
      List<PullRequest> pullRequests,
      List<Milestone> milestones) {

    Collections.sort(
        issues,
        new Comparator<Issue>() {
          @Override
          public int compare(Issue i1, Issue i2) {
            return i2.createdDate.compareTo(i1.createdDate);
          }
        });

    Collections.sort(
        postings,
        new Comparator<Posting>() {
          @Override
          public int compare(Posting p1, Posting p2) {
            return p2.createdDate.compareTo(p1.createdDate);
          }
        });

    Collections.sort(
        pullRequests,
        new Comparator<PullRequest>() {
          @Override
          public int compare(PullRequest p1, PullRequest p2) {
            return p2.created.compareTo(p1.created);
          }
        });

    Collections.sort(
        milestones,
        new Comparator<Milestone>() {
          @Override
          public int compare(Milestone m1, Milestone m2) {
            return m2.title.compareTo(m1.title);
          }
        });
  }
Example #19
0
 /**
  * Returns a TreeMap containing {@code n} values of a given Function {@code f} over a range of
  * integer values from 0 to {@code n - 1}.
  *
  * @param <K> The key type
  * @param <V> The value type
  * @param keyComparator The comparator used to sort the entries by their key
  * @param n The number of elements in the TreeMap
  * @param f The Function computing element values
  * @return A TreeMap consisting of elements {@code f(0),f(1), ..., f(n - 1)}
  * @throws NullPointerException if {@code keyComparator} or {@code f} are null
  */
 @SuppressWarnings("unchecked")
 public static <K, V> TreeMap<K, V> tabulate(
     Comparator<? super K> keyComparator,
     int n,
     Function<? super Integer, ? extends Tuple2<? extends K, ? extends V>> f) {
   Objects.requireNonNull(keyComparator, "keyComparator is null");
   Objects.requireNonNull(f, "f is null");
   return ofEntries(
       keyComparator,
       Collections.tabulate(n, (Function<? super Integer, ? extends Tuple2<K, V>>) f));
 }
Example #20
0
 private void sort() {
   Collections.sort(
       array_,
       new Comparator /*<RubyValue>*/() {
         public int compare(Object /*RubyValue*/ arg0, Object /*RubyValue*/ arg1) {
           RubyValue v =
               RubyAPI.callPublicOneArgMethod(
                   (RubyValue) arg0, (RubyValue) arg1, null, RubyID.unequalID);
           return ((RubyFixnum) v).toInt();
         }
       });
 }
  public static void main(String[] args) {
    Class student = Student.class;
    Method[] methods = student.getDeclaredMethods();

    ArrayList<String> methodList = new ArrayList<>();
    for (Method method : methods) {
      methodList.add(method.getName());
    }
    Collections.sort(methodList);
    for (String name : methodList) {
      System.out.println(name);
    }
  }
Example #22
0
  private void sort_with_block(final RubyBlock block) {
    final RubyArray self = this;
    Collections.sort(
        array_,
        new Comparator /*<RubyValue>*/() {

          public int compare(Object /*RubyValue*/ arg0, Object /*RubyValue*/ arg1) {
            // TODO can not check if block return/break occured.
            RubyValue v = block.invoke(self, (RubyValue) arg0, (RubyValue) arg1);
            return ((RubyFixnum) v).toInt();
          }
        });
  }
 public ListNode pollMin() {
   ListNode result = minHeap.get(0);
   if (result.next == null) {
     int lastIndex = minHeap.size() - 1;
     Collections.swap(minHeap, 0, lastIndex);
     minHeap.remove(lastIndex);
     nodeDown(0);
   } else {
     minHeap.set(0, result.next);
     nodeDown(0);
   }
   return result;
 }
Example #24
0
 public List<Interval> merge(List<Interval> intervals) {
   List<Interval> res = new ArrayList<>();
   Collections.sort(intervals, (Interval i1, Interval i2) -> i1.start - i2.start);
   Interval pre = null;
   for (Interval i : intervals) {
     if (res.isEmpty() || i.start > pre.end) {
       res.add(i);
       pre = i;
     } else {
       pre.end = Math.max(pre.end, i.end);
     }
   }
   return res;
 }
 public void nodeDown(int index) {
   while (true) {
     int minIndex = index;
     if (2 * index + 1 < minHeap.size()
         && minHeap.get(2 * index + 1).val < minHeap.get(minIndex).val) minIndex = 2 * index + 1;
     if (2 * index + 2 < minHeap.size()
         && minHeap.get(2 * index + 2).val < minHeap.get(minIndex).val) minIndex = 2 * index + 2;
     if (minIndex == index) break;
     else {
       Collections.swap(minHeap, index, minIndex);
       index = minIndex;
     }
   }
   return;
 }
 public MoPubClientPositioning addFixedPosition(int i) {
   boolean flag;
   if (i >= 0) {
     flag = true;
   } else {
     flag = false;
   }
   int j;
   if (com.mopub.common.Preconditions.NoThrow.checkArgument(flag)) {
     if ((j = Collections.binarySearch(mFixedPositions, Integer.valueOf(i))) < 0) {
       mFixedPositions.add(~j, Integer.valueOf(i));
       return this;
     }
   }
   return this;
 }
  public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
    if (intervals == null || intervals.size() <= 1) return intervals;

    Collections.sort(intervals, new IntervalComparator());
    ArrayList<Interval> res = new ArrayList<Interval>();
    Interval last = intervals.get(0);
    for (int i = 1; i < intervals.size(); i++) {
      Interval curt = intervals.get(i);
      if (last.end < curt.start) {
        res.add(last);
        last = curt;
      } else {
        last.end = Math.max(last.end, curt.end);
      }
    }
    res.add(last);
    return res;
  }
 public int[] maxSlidingWindow(int[] nums, int k) {
   int n = nums.length;
   if (n == 0) return new int[0];
   PriorityQueue<Integer> pq = new PriorityQueue<>(k, Collections.reverseOrder());
   Deque<Integer> queue = new ArrayDeque<>();
   for (int i = 0; i < k; ++i) {
     add(pq, queue, nums[i]);
   }
   if (n == k) return new int[] {pq.poll().intValue()};
   int[] max = new int[n - k + 1];
   int idx = 0;
   for (int i = k; i < n; ++i) {
     max[idx++] = pq.peek().intValue();
     pq.remove(queue.poll());
     add(pq, queue, nums[i]);
   }
   max[idx] = pq.peek().intValue();
   return max;
 }
Example #29
0
  // As an owner, I want the entry of an item to have minimal required
  // navigation in the user interface. It must be easy to describe an item.
  // http://stackoverflow.com/questions/18441846/how-to-sort-an-arraylist-in-java
  public void testSortAlpha() {
    ArrayList<GCard> gcards = new ArrayList<GCard>();
    GCard gcard1 =
        new GCard("Starbucks", 20, 1, 4, "Food & Drink", True, "Will get you half a coffee");
    gcards.add(gcard1);
    GCard gcard2 = new GCard("Cineplex", 50, 75, 5, "Entertainment", False, "I might keep these");
    gcards.add(gcard2);
    // <gcard1, gcard2>

    Collections.sort(
        gcards,
        new Comparator<GCard>() {
          @Override
          public int compare(GCard card1, GCard card2) {
            return card1.getName().compareTo(card2.getName());
          }
        });
    assertTrue((gcards.get(0) == gcard2) && (gcards.get(1) == gcard1));
    // <gcard2, gcard1>
  }
 /**
  * @param root: The root of binary tree.
  * @return: buttom-up level order a list of lists of integer
  */
 public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
   // write your code here
   Queue<TreeNode> q = new LinkedList<TreeNode>();
   ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
   if (root == null) return res;
   q.add(root);
   while (!q.isEmpty()) {
     ArrayList<Integer> cur = new ArrayList<Integer>();
     int size = q.size();
     for (int i = 0; i < size; i++) {
       TreeNode temp = q.poll();
       cur.add(temp.val);
       if (temp.left != null) q.add(temp.left);
       if (temp.right != null) q.add(temp.right);
     }
     res.add(cur);
   }
   Collections.reverse(res);
   return res;
 }