最接近点对问题一维java
时间: 2024-05-30 07:15:42 浏览: 9
以下是一维最接近点对问题的Java代码:
import java.util.Arrays;
public class ClosestPair1D {
public static void main(String[] args) {
double[] points = {1.2, 3.5, 0.8, 2.9, 4.1, 1.7};
System.out.println("Closest pair distance: " + closestPair(points));
}
public static double closestPair(double[] points) {
Arrays.sort(points);
double minDistance = Double.POSITIVE_INFINITY;
for (int i = 0; i < points.length - 1; i++) {
double distance = points[i + 1] - points[i];
if (distance < minDistance) {
minDistance = distance;
}
}
return minDistance;
}
}
该代码将一维点数组作为输入,并使用Java的Arrays.sort方法对其进行排序。然后,它在排序后的数组中遍历每个点对,并计算它们之间的距离。最后,该代码返回最接近的点对之间的距离。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)