1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| package questions;
import java.util.*;
public class _2406将区间分为最少组数 {
public int minGroups_gov(int[][] intervals) { Arrays.sort(intervals, (a, b) -> { int temp = a[0] - b[0]; return temp != 0 ? temp : -a[1] + b[1]; }); PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int[] interval : intervals) { if (!pq.isEmpty() && pq.peek() < interval[0]) pq.poll(); pq.add(interval[1]); } return pq.size(); }
public int minGroups_optimize(int[][] intervals) { List<int[]> list = new ArrayList<>(); for (int[] interval : intervals) { list.add(interval); } Collections.sort(list, (a, b) -> { int temp = a[0] - b[0]; return temp != 0 ? temp : -a[1] + b[1]; });
int res = 0; List<Integer> listIdx; while (!list.isEmpty()) { int right = 0; listIdx = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { int[] poll = list.get(i); if (right <= poll[0]) { listIdx.addFirst(i); right = poll[1]; } } for (Integer idx : listIdx) { List<int[]> listTemp = list.subList(0, idx); listTemp.addAll(list.subList(idx + 1, list.size())); list = listTemp; } res++; } return res; }
public int minGroups(int[][] intervals) { PriorityQueue<int[]> pq1 = new PriorityQueue<>((a, b) -> { int temp = a[0] - b[0]; return temp != 0 ? temp : -a[1] + b[1]; }); PriorityQueue<int[]> pq2 = new PriorityQueue<>((a, b) -> { int temp = a[0] - b[0]; return temp != 0 ? temp : -a[1] + b[1]; }); for (int[] interval : intervals) { pq1.offer(interval); }
int res = 0; boolean isOne = true; while (!pq1.isEmpty() || !pq2.isEmpty()) { int right = 0; if (isOne) { while (!pq1.isEmpty()) { int[] poll = pq1.poll(); if (right > poll[0]) { pq2.add(poll); } else { right = poll[1]; } } res++; isOne = false; } else { while (!pq2.isEmpty()) { int[] poll = pq2.poll(); if (right > poll[0]) { pq1.add(poll); } else { right = poll[1]; } } res++; isOne = true; } } return res; }
public static void main(String[] args) { _2406将区间分为最少组数 minGroups = new _2406将区间分为最少组数(); System.out.println(minGroups.minGroups_optimize(new int[][]{
{441459, 446342}, {801308, 840640}, {871890, 963447}, {228525, 336985}, {807945, 946787}, {479815, 507766}, {693292, 944029}, {751962, 821744} })); } }
|