第五天打卡
一、排序API相关
推荐文章:《LeetCode零基础指南》(第六讲)C排序API
二、题目
1、排序数组
int cmp(int *a,int *b){ return (*(int *)a)-(*(int *)b); } int* sortArray(int* nums, int numsSize, int* returnSize){ qsort(nums,numsSize,sizeof(int),cmp); *returnSize = numsSize; return nums; }
2、多数元素
int cmp(int *a,int *b){ return (*(int *)a)-(*(int *)b); } int majorityElement(int* nums, int numsSize){ qsort(nums,numsSize,sizeof(int ),cmp); return nums[numsSize/2]; }
3、存在重复元素
int cmp(int *a,int *b){ return (*(int*)a)-(*(int*)b); } bool containsDuplicate(int* nums, int numsSize){ qsort(nums,numsSize,sizeof(int ),cmp); for(int i=1;i4、最大间距
int cmp(int *a,int *b){ return (*(int *)a)-(*(int *)b); } int maximumGap(int* nums, int numsSize){ int max=0; qsort(nums,numsSize,sizeof(int),cmp); for(int i=1;imax){ max = nums[i]-nums[i-1]; } } return max; } 5、按奇偶排序数组
int qua(int x){ return x%2; } int cmp(int *a,int *b){ return qua(*(int *)a)-qua(*(int *)b); } int* sortArrayByParity(int* nums, int numsSize, int* returnSize){ int *ret = (int *)malloc(numsSize*sizeof(int )); qsort(nums,numsSize,sizeof(int ),cmp); for(int i=0;i6、最小时间差
int cmp(int *a,int *b){ return (*(int *)a)-(*(int *)b); } int min(int a,int b){ return a>b?b:a; } int findMinDifference(char ** timePoints, int timePointsSize){ int ans=1440; int *ret = (int *)malloc(timePointsSize*sizeof(int )); int i,a,b; for(i=0;isscanf()函数学习
7、三角形的最大周长
int cmp(int *a,int *b){ return *(int *)a-*(int *)b; } int largestPerimeter(int* nums, int numsSize){ qsort(nums,numsSize,sizeof(int ),cmp); for(int i=numsSize-1;i>=2;--i){ if(nums[i-2]+nums[i-1]>nums[i]){ return nums[i-2]+nums[i-1]+nums[i]; } } return 0; }8、救生艇
![int cmp(int *a,int *b){ return *(int *)a-*(int *)b; } int numRescueBoats(int* people, int peopleSize, int limit){ int ans=0; int i=0;int r=peopleSize-1; qsort(people,peopleSize,sizeof(int ),cmp); while(i<=r){ if(i==r){ ++ans;break; }else if(people[i]+people[r]>limit){ ++ans;r--; }else{ ++ans;i++;r--; } } return ans; }欢迎分享,转载请注明来源:内存溢出
评论列表(0条)