AcWing 906. 区间分组JAVA
原题链接
简单
作者:
ARM
,
2020-08-23 11:49:01
,
所有人可见
,
阅读 436
java 超时代码
import java.io.*;
import java.lang.*;
import java.util.*;
class Main{
static int n = 0, N = 100010;
static int[] groups = new int[N];
static int group = 0;
public static void main(String[] args)throws Exception{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
n = Integer.valueOf(buf.readLine());
int[][] nums = new int[n][2];
int t = 0;
while(n-- != 0){
String[] info = buf.readLine().split(" ");
int a = Integer.valueOf(info[0]);
int b = Integer.valueOf(info[1]);
nums[t][0] = a;
nums[t][1] = b;
t++;
}
Arrays.fill(groups, -0x3f3f3f3f);
Arrays.sort(nums, (a,b)->{return a[0] - b[0];});//排序
for(int i = 0; i < t; ++i){
boolean flag = false;
for(int j = 0; j <= group; ++j){
if(nums[i][0] > groups[j]){
flag = true;
groups[j] = nums[i][1];
break;
}
}
if(!flag)groups[++group] = nums[i][1];
}
System.out.print(group + 1);
}
}
java 小根堆优化代码
import java.io.*;
import java.lang.*;
import java.util.*;
class Main{
static int n = 0, N = 100010;
static PriorityQueue<Integer> qu = new PriorityQueue<>();
public static void main(String[] args)throws Exception{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
n = Integer.valueOf(buf.readLine());
int[][] nums = new int[n][2];
int t = 0;
while(n-- != 0){
String[] info = buf.readLine().split(" ");
int a = Integer.valueOf(info[0]);
int b = Integer.valueOf(info[1]);
nums[t][0] = a;
nums[t][1] = b;
t++;
}
Arrays.sort(nums, (a,b)->{return a[0] - b[0];});//排序
for(int i = 0; i < t; ++i){
if(qu.isEmpty() || qu.peek() >= nums[i][0]){
qu.offer(nums[i][1]);
}else if(qu.peek() < nums[i][0]){
qu.poll();
qu.offer(nums[i][1]);
}
}
System.out.print(qu.size());
}
}