题目:
思路:首先关于区间的选取,要选择结束时间最早的区间,因此就要对结束时间进行排序,那么如何能保证,开始时间会随着结束时间一起排序呢?
就要用到面向对象的特点进行打包。
import java.util.Arrays;
import java.util.Scanner;
public class 区间调度 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] s=new int[n];//起始时间
int[] t=new int[n];//结束时间
Job[] jobs=new Job[n];
for (int i = 0; i < n; i++) {
s[i]=sc.nextInt();
}
for (int i = 0; i < n; i++) {
t[i]=sc.nextInt();
}
for (int i = 0; i < n; i++) {
jobs[i]=new Job(s[i],t[i]);
}
Arrays.sort(jobs);//因为有了接口,此处可以排序
int res=f(n,jobs);
System.out.println(res);
}
private static int f(int n,Job[] jobs) {
int cnt=1;
int y=jobs[0].t;//y指向每个区间的结束时间
for (int i = 0; i < n; i++) {
if (jobs[i].s>y) {//下一个的起始时间比y大,则计入
cnt++;
y=jobs[i].t;
}
}
return cnt;
}
//接口,使其必须实现排序规则
private static class Job implements Comparable<Job>{
int s;
int t;
public Job(int s,int t) {
this.s=s;
this.t=t;
}
public int compareTo(Job other) {
int x=this.t-other.t;
if(x==0)
return this.s-other.s;
else
return x;
}
}
}