import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] positions = new int[n]; for (int i = 0; i < n; i++) { positions[i] = sc.nextInt(); } int m = sc.nextInt(); System.out.println(getResult(n, positions, m)); } public static int getResult(int n, int[] positions, int m) { Arrays.sort(positions); int min = 1, max = positions[n - 1] - positions[0]; int ans = 0; while (min <= max) { int mid = (min + max) >> 1; if (check(positions, m, mid)) { ans = mid; min = mid + 1; } else { max = mid - 1; } } return ans; } public static boolean check(int[] positions, int m, int minDis) { int count = 1; int curPos = positions[0]; for (int i = 1; i < positions.length; i++) { if (positions[i] - curPos >= minDis) { count++; curPos = positions[i]; } } return count >= m; } }把这段Java代码转成C++
时间: 2024-04-11 16:28:48 浏览: 105
Sure! Here's the equivalent code in C++:
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int getResult(int n, vector<int>& positions, int m) {
sort(positions.begin(), positions.end());
int minDis = 1;
int maxDis = positions[n - 1] - positions[0];
int ans = 0;
while (minDis <= maxDis) {
int mid = (minDis + maxDis) >> 1;
int count = 1;
int curPos = positions[0];
for (int i = 1; i < n; i++) {
if (positions[i] - curPos >= mid) {
count++;
curPos = positions[i];
}
}
if (count >= m) {
ans = mid;
minDis = mid + 1;
} else {
maxDis = mid - 1;
}
}
return ans;
}
int main() {
int n;
cin >> n;
vector<int> positions(n);
for (int i = 0; i < n; i++) {
cin >> positions[i];
}
int m;
cin >> m;
cout << getResult(n, positions, m) << endl;
return 0;
}
```
You can now use this C++ code to achieve the same functionality as the original Java code.
阅读全文