中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
写了下第一轮第二问,楼主可以详细讲讲第三问怎么做吗?
- public class Straight {
-
- static class Point {
- int val;
- int count;
-
- public Point(int val, int count) {
- this.val = val;
- this.count = count;
- }
- }
- public static boolean isExactXStraight(int[] nums, int x) {
- if (nums == null || nums.length < x) {
- return false;
- }
- PriorityQueue<Point> pq = new PriorityQueue<Point>(11, new Comparator<Point>() {
- public int compare(Point p1, Point p2) {
- return p1.val - p2.val;
- }
- });
- HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
- for (int i : nums) {
- if (map.containsKey(i)) {
- map.put(i, map.get(i) + 1);
- } else {
- map.put(i, 1);
- }
- }
- for (int key : map.keySet()) {
- pq.offer(new Point(key, map.get(key)));
- }
- while (!pq.isEmpty()) {
- List<Point> list = new ArrayList<Point>();
- Point prev = pq.poll();
- list.add(prev);
- for (int i = 1; i < x; i++) {
- if (pq.isEmpty()) {
- return false;
- }
- Point cur = pq.poll();
- list.add(cur);
- if (cur.val != prev.val + 1) {
- return false;
- }
- prev = cur;
- }
- for (Point p : list) {
- p.count = p.count - 1;
- if (p.count != 0) {
- pq.offer(p);
- }
- }
- }
-
- return true;
- }
-
- public static void main(String[] args) {
- int[] nums = {1, 2, 3, 4, 4, 5, 5, 6, 7, 8};
- boolean res = isExactXStraight(nums, 5);
- System.out.println(res);
- }
- }
复制代码 |
|