classSolution{public:intintersectionSizeTwo(vector<vector<int>>&intervals){intans=0;intmax=-1;intsecondMax=-1;sort(begin(intervals),end(intervals),[](constauto&a,constauto&b){returna[1]==b[1]?a[0]>b[0]:a[1]<b[1];});for(constauto&interval:intervals){constinta=interval[0];constintb=interval[1];// max and 2nd max still satisfyif(max>=a&&secondMax>=a)continue;if(max>=a){// max still satisfysecondMax=max;max=b;// add b to the set Sans+=1;}else{// max and 2nd max can't satisfymax=b;// add b to the set SsecondMax=b-1;// add b - 1 to the set Sans+=2;}}returnans;}};
JAVA
classSolution{publicintintersectionSizeTwo(int[][]intervals){intans=0;intmax=-1;intsecondMax=-1;Arrays.sort(intervals,(a,b)->a[1]==b[1]?b[0]-a[0]:a[1]-b[1]);for(int[]interval:intervals){finalinta=interval[0];finalintb=interval[1];// max and 2nd max still satisfyif(max>=a&&secondMax>=a)continue;if(max>=a){// max still satisfysecondMax=max;max=b;// add b to the set Sans+=1;}else{// max and 2nd max can't satisfymax=b;// add b to the set SsecondMax=b-1;// add b - 1 to the set Sans+=2;}}returnans;}}
Login to Codeflu
Log in to stay update and get notify on new arrivals.