leetcode重点分类(C语言) - 排序

 分类参考:https://github.com/CyC2018/CS-Notes/blob/master/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E7%9B%AE%E5%BD%95.md

 

215. 数组中的第K个最大元素

int cmp(const void* a, const void* b)
{
    return *(int*)a - *(int*)b;
}

int findKthLargest(int* nums, int numsSize, int k)
{
    qsort(nums, numsSize, sizeof(int), cmp);
    return nums[numsSize - k];
}

 

347. 前 K 个高频元素

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

int c1(const int* a,const int* b)
{
    return (*a - *b);
}

int c2(const void* a,const void* b)
{
    int* m = *(int**)a;
    int* n = *(int**)b;
    return (n[1] - m[1]);
}

int* topKFrequent(int* nums, int numsSize, int k, int* returnSize)
{
    int** hash = (int**)malloc(numsSize * sizeof(int*));
    qsort(nums, numsSize, sizeof(int), c1);
    int m = 0;
    for(int i = 0; i < numsSize; i++) {
        if(m == 0) {
            hash[m] = calloc(2, sizeof(int));
            hash[m][0] = nums[i];
            hash[m][1] = 1;
            m++;
        }
        else if (nums[i] == hash[m-1][0]) {
            hash[m-1][1]++;
        } 
        else {
            hash[m] = calloc(2, sizeof(int));
            hash[m][0] = nums[i];
            hash[m][1] = 1;
            m++;
        }
    }
    qsort(hash, m, sizeof(hash[0]), c2);
    int* a = calloc(k, sizeof(int));
    for(int i = 0; i < k; i++) {
        a[i] = hash[i][0];
    }
    *returnSize = k;
    return a;
}

 

451. 根据字符出现频率排序

int compare(const void* a, const void* b) 
{
    return ((int*)b)[0]-((int*)a)[0]; 
}

char* frequencySort(char* s)
{
    int hash[128] = {0};
    int arr[128][2] = {0};
    int len = strlen(s);
    int size = 0;
    for (int i = 0; i < len; i++) {
        hash[s[i]]++;
    } 
    for (int i = 0; i < 128; i++) {
        if (hash[i] > 0) {
            arr[size][0] = hash[i];
            arr[size][1] = i;
            size++;
        }
    }  
    qsort(arr, size, sizeof(arr[0]), compare);
    for (int i = 0, j = 0; i < size; i++) {
        if (arr[i][0] > 0) {
            s[j++] = arr[i][1];
            arr[i][0]--;
            i--;
        }
    }
    return s;
}

 

75. 颜色分类

void sortColors(int* nums, int numsSize)
{
    int i = 0, count1 = 0, count2 = 0, index = 0;
    for (i = 0; i < numsSize; i++) {
        if (nums[i] == 1) {
            count1++;
        }
        else if (nums[i] == 2) {
            count2++;
        }  
    }
    for(i = 0; i < numsSize - count1 - count2; i++) {
        nums[index++] = 0;
    }
    for(i = 0; i < count1; i++) {
        nums[index++] = 1;
    }
    for(i = 0; i < count2; i++) {
        nums[index++] = 2;
    } 
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值