1.先排序,再一层遍历。
class Solution {
public:
int specialArray(vector<int>& nums) {
sort(nums.begin(),nums.end());
int n=nums.size();
for(int i=0;i<n;i++){
if(nums[i]>=n-i){
if(i==0|| nums[i-1]<n-i){
return n-i;
}
}
}
return -1;
}
};
2.构建二分。
class Solution {
public:
int shipWithinDays(vector<int>& weights, int days) {
int left = *max_element(weights.begin(), weights.end());
int right = accumulate(weights.begin(), weights.end(), 0);
while (left < right) {
int mid = (left + right) / 2;
int need = 1, cur = 0;
for (int weight: weights) {
if (cur + weight > mid) {
++need;
cur = 0;
}
cur += weight;
}
if (need <= days) {
right = mid;
}
else {
left = mid + 1;
}
}
return left;
}
};
3.这题暴力解法会超时,所以在内层循环用二分。
class Solution {
public:
vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
sort(potions.begin(),potions.end());
int n=spells.size();
int m=potions.size();
vector<int>pairs(n);
for(int i=0;i<n;i++){
int left=0,right=m-1;
while(left<=right){
int mid=left+(right-left)/2;
if(potions[mid]<(double)success/(double)spells[i]){
left=mid+1;
}else{
right=mid-1;
}
}
pairs[i]=m-left;
}
return pairs;
}
};