class Solution {
public:
int largestPerimeter(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
for(int i = n; i > 2; i--)
{
if(nums[i - 1] < nums[i - 2] + nums[i - 3])
{
return nums[i - 1] + nums[i - 2] + nums[i - 3];
}
}
return 0;
}
};
第三题 数组拆分
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
if(nums.size() < 2)
return 0;
sort(nums.begin(), nums.end());
int n = nums.size() / 2;
int sum = 0;
for(int i = 0; i < n; i++)
{
sum += nums[2 * i];
}
return sum;
}
};
第四题 救生艇 贪心+双指针
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
//贪心双指针,要让做两个人的船尽可能地多
int n = people.size();
sort(people.begin(), people.end());
if(people[0] >= limit)
return n;
int ans = 0;
int l = 0;
int r = people.size() - 1;
while(l <= r)
{
//最后单独仅剩一人情况
if(l == r)
{
ans++;
break;
}
if(people[l] + people[r] <= limit)
{
ans++;
l++;
r--;
}
else
{
ans++;
r--;
}
}
return ans;
}
};
第五题 摆动排序Ⅱ
class Solution {
public:
void wiggleSort(vector<int>& nums) {
//太秀了
vector<int> tmp = nums;
sort(tmp.begin(), tmp.end());
int i;
int r = nums.size() - 1;
for(i = 1; i < nums.size(); i += 2)
{
nums[i] = tmp[r--];
}
for(i = 0; i < nums.size(); i+=2)
{
nums[i] = tmp[r--];
}
}
};
第六题 分发饼干
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int mn = min(g.size(), s.size());
int p1 = 0;
int p2 = 0;
int ans = 0;
while(p1 < g.size() && p2 < s.size())//小孩分完了 或 饼干分完了 就退出
{
if(g[p1] > s[p2])
{
p2++;
}
else
{
ans++;
p1++;
p2++;
}
}
return ans;
}
};
class Solution {
public:
int minIncrementForUnique(vector<int>& nums) {
//转换成最小操作数使元素递增
sort(nums.begin(),nums.end());
int n = nums.size();
int cnt = 0;
for(int i = 1; i < n; i++){
if(nums[i] <= nums[i-1]){
cnt += nums[i-1] + 1 - nums[i];
nums[i] = nums[i-1] + 1;
}
}
return cnt;
}
};
第九题 有效三角形个数
class Solution {
public:
int triangleNumber(vector<int>& nums) {
//排序 + 枚举 + 二分查找
sort(nums.begin(), nums.end());
int ans = 0;
int n = nums.size();
for(int i = 0; i < n; ++i)
{
for(int j = i + 1; j < n; j++)
{
int left = j + 1;
int right = n - 1;
int k = j;
while(left <= right)
{
int mid = (left + right) / 2;
if(nums[mid] >= nums[i] + nums[j])
{
right = mid - 1;
}
else
{
k = mid;
left = mid + 1;
}
}
ans += k - j;
}
}
return ans;
}
};