728x90
반응형
https://www.lintcode.com/problem/920/
https://www.acmicpc.net/problem/1931
끝나는 시간 기준 오름차순 정렬, 끝나는 시간이 같으면 시작 시간 기준 오름차순
import java.util.*;
class Main{
public static boolean main(String args[]) throws Exception{
Scanner sc = new Scanner(System.in);
int N=sc.nextInt();
int[][] arr =new int[N][2];
//시작 시간, 끝나는 시간
for(int i=0;i<N;i++){
arr[i][0]=sc.nextInt();
arr[i][1]=sc.nextInt();
}
Arrays.sort(arr, (o1, o2) -> {
if(o1[1] == o2[1]){
return Integer.compare(o1[0], o2[0]);
} else {
return Integer.compare(o1[1], o2[1]);
}
});
int cnt=0;
int end=Integer.MIN_VALUE;
for(int i=0;i<N;i++){
if(arr[i][0]>=end){
cnt++;
end=arr[i][1];
}
}
if(cnt==N){
return boolean flag=true;
}
else return boolean flag=false;
}
}
백준
import java.util.*;
class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int [][] arr = new int[n][2];
for(int i=0;i<n;i++){
arr[i][0]=in.nextInt();
arr[i][1]=in.nextInt();
}
Arrays.sort(arr, (o1, o2)->o1[1]==o2[1]?o1[0]-o2[0]: o1[1]-o2[1]);
//for(int[] a : arr) System.out.println(a[0]+" "+a[1]);
System.out.println(Solution(n,arr));
}
private static int Solution(int n, int[][] arr){
int start=0;
int end=0;
int cnt=0;
for(int i=0;i<n;i++){
if(arr[i][0]>=end){
cnt++;
end=arr[i][1];
}
}
return cnt;
}
}
리트코드
package Ch2_sorting_search.Q5;
import java.util.*;
class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int [][] arr = new int[n][2];
for(int i=0;i<n;i++){
arr[i][0]=in.nextInt();
arr[i][1]=in.nextInt();
}
Arrays.sort(arr, (o1, o2)->o1[1]==o2[1]?o1[0]-o2[0]: o1[1]-o2[1]);
//for(int[] a : arr) System.out.println(a[0]+" "+a[1]);
System.out.println(Solution(n,arr));
}
private static boolean Solution(int n, int[][] arr){
int start=0;
int end=0;
int cnt=0;
for(int i=0;i<n;i++){
if(arr[i][0]>=end){
cnt++;
end=arr[i][1];
}
}
return cnt==n?true:false;
}
}
public class Solution {
public boolean canAttendMeetings(List<Interval> intervals) {
int end=0;
int cnt=0;
Collections.sort(intervals, (o1,o2)-> o2.end==o1.end? o1.start-o2.start:o1.end-o2.end);
for(Interval i : intervals){
if(end<=i.start){
end=i.end;
}else{
return false;
}
}
return true;
}
}
728x90
반응형