# leetcode1552()-其他

## leetcode1552()

Category Difficulty Likes Dislikes
algorithms Medium (51.48%) 122 –
Tags
Unknown

Companies
Unknown

n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9

2 <= m <= position.length
Discussion | Solution

``````// 这题最大的纠结之处在于可以对原数组进行排序        最大化最小值 最小化最大值都可以用二分模板
class Solution {
public:
int maxDistance(vector<int>& position, int m) {
sort(position.begin(), position.end());
int l = 1, r = *max_element(position.begin(), position.end());
int ans = 1;
while(l < r)
{
int mid = l + ((r-l)>>1)+1;
long step = 1;
int index = 0;
for(int i=1;i<position.size();i++)
{
if(position[i] - position[index] >= mid)
{
step++;
index = i;
}
}
if(step<m)
{
ans = mid;
r = mid - 1;
}
else
l = mid;
}
return ans;
}
};
``````
————————

Category Difficulty Likes Dislikes
algorithms Medium (51.48%) 122 –
Tags
Unknown

Companies
Unknown

n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9

2 <= m <= position.length
Discussion | Solution

``````// 这题最大的纠结之处在于可以对原数组进行排序        最大化最小值 最小化最大值都可以用二分模板
class Solution {
public:
int maxDistance(vector<int>& position, int m) {
sort(position.begin(), position.end());
int l = 1, r = *max_element(position.begin(), position.end());
int ans = 1;
while(l < r)
{
int mid = l + ((r-l)>>1)+1;
long step = 1;
int index = 0;
for(int i=1;i<position.size();i++)
{
if(position[i] - position[index] >= mid)
{
step++;
index = i;
}
}
if(step<m)
{
ans = mid;
r = mid - 1;
}
else
l = mid;
}
return ans;
}
};
``````