原题链接:1608. 特殊数组的特征值
solution: 排序+二分查找+暴力
class Solution {
public:
//求出大于等于target的个数
int summary(vector<int>& nums, int target)
{
int l = 0,r = nums.size()-1;
while(l < r){
int mid = l + r >> 1;
if(nums[mid] >= target) r = mid;
else l = mid + 1;
}
return nums.size() - l;
}
int specialArray(vector<int>& nums) {
sort(nums.begin(),nums.end()); //先排序
for(int i = 0;i <= nums.back();i++){
if(summary(nums, i) == i)
return i;
}
return -1;
}
};
###优化后
class Solution {
public:
//求出大于等于target的个数
int summary(vector<int>& nums, int target)
{
int l = 0,r = nums.size()-1;
while(l < r){
int mid = l + r >> 1;
if(nums[mid] >= target) r = mid;
else l = mid + 1;
}
if(nums[l]<target) return 0;
return nums.size() - l;
}
int specialArray(vector<int>& nums) {
int n = nums.size();//数组大小
sort(nums.begin(), nums.end());
int l = 0, r = 1000;
while (l < r) {
int mid = (l + r)>>1;
if (summary(nums, mid) <= mid)
r = mid;
else
l = mid + 1;
}
if(summary(nums, l) == l) return l;
return -1;
}
};