文章目录
题目
题解
题目
1351. 统计有序矩阵中的负数
剑指 Offer II 069. 山峰数组的顶部
852. 山脉数组的峰顶索引
剑指 Offer 57. 和为s的两个数字 双指针
剑指 Offer II 006. 排序数组中两个数字之和
888. 公平的糖果棒交换
1608. 特殊数组的特征值
1608. 特殊数组的特征值
题解
1351. 统计有序矩阵中的负数
int countNegatives(int** grid, int gridSize, int* gridColSize){ int low = 0,high = gridColSize[0],ans= 0; for(int i = 0;i < gridSize;i++){ low = 0;//由于按列非递增 所以不用更新high while(low<high){ int mid = (low + high) /2; if(grid[i][mid] >= 0) low = mid + 1; else high = mid; } ans += gridColSize[i] - high; } return ans; }
剑指 Offer II 069. 山峰数组的顶部
int peakIndexInMountainArray(int* arr, int arrSize){ int low = 1,high = arrSize -2,ans = 0; while(low <= high){ int mid = (low + high)/2; if(arr[mid] > arr[mid-1]){ ans = mid; low = mid + 1; } else high = mid - 1; } return ans; }
剑指 Offer 57. 和为s的两个数字
int* twoSum(int* nums, int numsSize, int target, int* returnSize){ int low = 0,high = numsSize - 1,*ans = malloc(sizeof(int)*2); *returnSize = 2; while(low < high){ if(nums[low] + nums[high] > target) high--; else if(nums[low] + nums[high] == target) break; else low++; } ans[0] = nums[low]; ans[1] = nums[high]; return ans; }
剑指 Offer II 006. 排序数组中两个数字之和
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){ int low = 0,high = numbersSize - 1,*ans = malloc(sizeof(int)*2); *returnSize = 2; while(low < high){ if(numbers[low] + numbers[high] > target) high--; else if(numbers[low] + numbers[high] == target) break; else low++; } ans[0] = low; ans[1] = high; return ans; }
888. 公平的糖果棒交换
int cmp(int *a,int *b){ return *a>*b; } int* fairCandySwap(int* aliceSizes, int aliceSizesSize, int* bobSizes, int bobSizesSize, int* returnSize){ int sum1= 0,sum2 = 0,low = 0,high = 0,*ans = malloc(sizeof(int)*2); *returnSize = 2; for(int i = 0;i < aliceSizesSize;i++) sum1 += aliceSizes[i]; for(int i = 0;i < bobSizesSize;i++) sum2 += bobSizes[i]; sum2 -= sum1; sum2/=2; qsort(aliceSizes,aliceSizesSize,sizeof(int),cmp); qsort(bobSizes,bobSizesSize,sizeof(int),cmp); while(low < aliceSizes && high < bobSizesSize){ if(bobSizes[high] - aliceSizes[low] > sum2) low++; else if(bobSizes[high] - aliceSizes[low] == sum2) break; else high++; } ans[0] = aliceSizes[low]; ans[1] = bobSizes[high]; return ans; }
1608. 特殊数组的特征值
int cmp(int *a,int *b){ return *a > *b; } int specialArray(int* nums, int numsSize){ int low = 0,ans = 0; qsort(nums,numsSize,sizeof(int),cmp); while(ans<=numsSize && low < numsSize){ while(low < numsSize&&nums[low] < ans) low++; if(ans == numsSize-low) return ans; ans++; } return -1; }
1608. 特殊数组的特征值
int search(int* nums, int numsSize, int target){ int low = 0,high = numsSize - 1; while(low <= high){ int mid = (low + high)/2; if(nums[mid] == target) return mid; else if(nums[mid] > target) high = mid-1; else low = mid + 1; } return -1; }