【leetcode】按照频率将数组升序排序
/** * Note: The returned array must be malloced, assume caller calls free(). */ typedef struct st{ int val; int cnt; }st; int cmp(const void* a,const void* b){ return ((*(st*)a).cnt != (*(st*)b).cnt)?(*(st*)a).cnt-(*(st*)b).cnt :(*(st*)a).val < (*(st*)b).val; } int* frequencySort(int* nums, int numsSize, int* returnSize){ st arr[201]={0}; int* ret = (int*)calloc(101,sizeof(int)); int i,pst=0,n=0; for(i=0; i<numsSize; ++i){ arr[nums[i]+100].val=nums[i]; arr[nums[i]+100].cnt++; } qsort(arr,201,sizeof(st),cmp); for(i=0; i<201; ++i){ while(arr[i].cnt){ ret[pst++]=arr[i].val; arr[i].cnt--; } } *returnSize=pst; return ret; }
/** * Note: The returned array must be malloced, assume caller calls free(). */ typedef struct st{ int val; int cnt; }st; int cmp(const void* a,const void* b){ return ((*(st*)a).cnt != (*(st*)b).cnt)?(*(st*)a).cnt-(*(st*)b).cnt :(*(st*)a).val < (*(st*)b).val; } int* frequencySort(int* nums, int numsSize, int* returnSize){ st arr[201]={0}; int* ret = (int*)calloc(101,sizeof(int)); int i,pst=0,n=0; for(i=0; i<numsSize; ++i){ arr[nums[i]+100].val=nums[i]; arr[nums[i]+100].cnt++; } qsort(arr,201,sizeof(st),cmp); for(i=0; i<201; ++i){ while(arr[i].cnt){ ret[pst++]=arr[i].val; arr[i].cnt--; } } *returnSize=pst; return ret; }