救生艇(双指针)
#include <stdio.h>
void quick_sort(int *a, int left, int right);
int numRescueBoats(int* people, int peopleSize, int limit);
int main()
{
int people[2] = {3, 2, 2, 1};
int limit = 3;
int nums = numRescueBoats(people, 4, 3);
printf("需要%d个救生艇", nums);
}
//快速排序
void quick_sort(int *a, int left, int right)
{
int i, j, t, temp;
if(left >= right)
return;
temp = a[left];
i = left;
j = right;
while(i != j)
{
while(a[j] >= temp && i < j)
{
j--;
}
while(a[i] <= temp && i < j)
{
i++;
}
if(i < j)
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
a[left] = a[i];
a[i] = temp;
quick_sort(a, left, i-1);
quick_sort(a, i+1, right);
return;
}
//leetcode-881
int numRescueBoats(int* people, int peopleSize, int limit)
{
quick_sort(people, 0, peopleSize-1);
int nums = 0;
int left = 0;
int right = peopleSize - 1;
while(left <= right)
{
if(people[left] + people[right] <= limit)
left++;
right--;
nums++;
}
return nums;
}