Delete occurrences of an element if it occurs more than n times(C語言CodeWars)

解題思路:

(1)建立一個hash表,用來記錄每個數字出現的次數

(2)兩個指針,一個記錄原數組的位置,一個記錄新數組的位置

#include <stddef.h>

int* delete_nth(size_t szin, int order[szin], int max_e, size_t *szout) {
   int *hash = (int*)calloc(10000,sizeof(int));
   int *s = (int*)calloc(100,sizeof(int));

   size_t i = 0,j=0;
   while(i<szin) {
      if(hash[order[i]]<max_e) {
         hash[order[i]]++;
         s[j]=order[i];
         i++;
         j++;
      } else i++;
   }
   *szout = j;
   free(hash);
   return s;
}

CodeWars測試:

#include <criterion/criterion.h>
#include <stdlib.h>
#include <stddef.h>

int* delete_nth(size_t szin, int order[szin], int max_e, size_t *szout);

void assert_int_arr_eq(size_t e, int expected[e], size_t s, int submitted[s]) {
    if(s != e) {
        cr_assert(0, "Incorrect array size:\n\n Expected %d  Submitted %d\n\n", e, s);
    }
    for(size_t i=0; i<e; i++) {
        if(submitted[i] != expected[i]) {
            cr_assert(0, "Incorrect Value at index %d:\n\n Expected %d  Submitted %d\n\n",
            i, expected[i], submitted[i]);
        }
    }
    cr_assert(1);
}

Test(Sample_Tests, should_pass_all_the_tests_provided) {
  {
    #define SZIN 4
    const int order[SZIN] = {20, 37, 20, 21};
    const int max_e = 1;
    #define SZEXP 3
    const int expected[SZEXP] = {20, 37, 21};
    size_t szout = NULL;
    const int* submitted = delete_nth(SZIN, order, max_e, &szout);
    assert_int_arr_eq(SZEXP, expected, szout, submitted);
    free(submitted); submitted = NULL;
  }
  {
    #define SZIN 9
    const int order[SZIN] = {1, 1, 3, 3, 7, 2, 2, 2, 2};
    const int max_e = 3;
    #define SZEXP 8
    const int expected[SZEXP] = {1, 1, 3, 3, 7, 2, 2, 2};
    size_t szout = NULL;
    const int* submitted = delete_nth(SZIN, order, max_e, &szout);
    assert_int_arr_eq(SZEXP, expected, szout, submitted);
    free(submitted); submitted = NULL;
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章