问题:
给一组间隔,找出一个点,使得穿过该点的间隔数最大, 时间复杂度不能超过 O(N lg N)。比如有一组间隔为[1, 5] [ 3, 7] [2, 4] [8, 9], 那么对于点 3.5, 有3个间隔都包含这个点,但是对于点 8.5,只有一个间隔包含该点。所以,最后答案是 3.5. (当然,3.6, 或者 3.7 都可以)。
分析:
对于一组间隔,我们把它所有间隔的起始值和结束值放在一起排序,每遇到一个间隔的起始值,我们把个数加1,遇到一个结束值,我们把个数减1,这样,我们可以得到最大个数。对于 “点” 的值,它一定是在一个结束值和一个起始值之间。
代码如下:
public class Test {
/*
* start: stores the start value of the intervals;
* end: stores the end value of the intervals
*/
public float findPoint(float[] start, float[] end) {
int currentInterval = 0;
int maximumInterval = 0;
float pointBeginValue = 0.0f;
float pointValue = 0.0f;
//store the interval start values into the list
ArrayList<Point> list = new ArrayList<Point>();
for (int i = 0; i < start.length; i++) {
list.add(new Point(start[i], true));
}
//store the interval end values into the list
for (int j = 0; j < end.length; j++) {
list.add(new Point(end[j], false));
}
//sort
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).bStart) {
currentInterval++;
if (currentInterval >= maximumInterval) {
maximumInterval = currentInterval;
pointBeginValue = list.get(i).value;
}
} else {
if (currentInterval == maximumInterval) {
pointValue = (pointBeginValue + list.get(i).value) / 2.0f;
}
currentInterval--;
}
}
return pointValue;
}
public static void main(String[] args) {
//start value of the interval
float[] start = {1.2f, 3, 5, 1, 2.4f};
//end value of the interval
float[] end = {2.3f, 4.5f, 7.9f, 2, 4};
System.out.println(new Test().findPoint(start, end));
}
}
class Point implements Comparable<Point>{
float value = 0.0f;
boolean bStart = false;
Point(float value, boolean bStart) {
this.value = value;
this.bStart = bStart;
}
public int compareTo(Point o) {
if (value > ((Point)o).value ) {
return 1;
} else if (value == ((Point)o).value) {
return 0;
}
return -1;
}
}
参考:http://haixiaoyang.wordpress.com/2012/03/19/find-the-point-intersect-with-most-intervals/
转载请注明出处:http://blog.csdn.net/beiyeqingteng