題目:
思路:首先關於區間的選取,要選擇結束時間最早的區間,因此就要對結束時間進行排序,那麼如何能保證,開始時間會隨着結束時間一起排序呢?
就要用到面向對象的特點進行打包。
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;
}
}
}