41. 缺失的第一个正数
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int firstMissingPositive(int* nums, int numsSize)
{
if (numsSize < 1) {
return 1;
}
int i = 0;
while (i < numsSize) {
if (nums[i] != i + 1 && nums[i] > 0 && nums[i] <= numsSize && nums[i] != nums[nums[i] - 1]) {
swap(nums + i, nums + nums[i] - 1);
} else {
i++;
}
}
for (i = 0; i < numsSize; i++) {
if (nums[i] != i + 1) {
break;
}
}
return i + 1;
}
42. 接雨水
int max(int a, int b)
{
return a >= b ? a : b;
}
int trap(int* height, int heightSize)
{
if(heightSize==0) {
return 0;
}
int left = 0, right = heightSize - 1;
int max_left = height[0], max_right = height[heightSize-1];
int ans = 0;
while(left <= right) {
max_left = max(max_left, height[left]);
max_right = max(max_right, height[right]);
if(max_left < max_right) {
ans = ans + max_left - height[left];
left++;
} else {
ans = ans + max_right - height[right];
right--;
}
}
return ans;
}
43. 字符串相乘
char* multiply(char* num1, char* num2)
{
int* sum = (int*)calloc(220, sizeof(int));
if(num1 == NULL || num2 == NULL || num1[0] == '0' || num2[0] == '0') {
char* result = (char*)calloc(2, sizeof(char));
result[0] = '0';
return result;
}
int l1 = strlen(num1);
int l2 = strlen(num2);
int i = 0, j = 0, t = 0, index = 0;
for(i = 0; i < l1; i++) {
for(j = 0; j < l2; j++) {
sum[i + j] += (num1[i] - '0') * (num2[j] - '0');
}
}
for(i = l1 + l2 - 2; i >= 0; i--) {
sum[i] += t;
if(sum[i] >= 10) {
t = sum[i] / 10;
sum[i] = sum[i] % 10;
}
else {
t = 0;
}
}
int len = 2 + (t ? l1 + l2 - 1 : l1 + l2 - 2);
char* result = (char*)malloc(len * sizeof(char));
if(t) {
result[index++] = '0' + t;
}
for(i = 0; i <= l1 + l2 - 2; i++) {
result[index++] = sum[i] + '0';
}
result[index] = 0;
free(sum);
return result;
}
44. 通配符匹配(待定)
45. 跳跃游戏 II
int jump(int* nums, int numsSize)
{
if(numsSize < 2) {
return 0;
}
int i, j;
int cur = 0;
int res = 0;
int max = -1;
for(i = 0; i < numsSize - 1; i++) {
max = max > i + nums[i] ? max : i + nums[i];
if(cur == i) {
res++;
cur = max;
}
}
return res;
}