2024年8月4日 星期日

[950] Reveal Cards In Increasing Order

看起來是一個可以用index 硬幹的題目(?)
數學不好真的很吃虧(牽拖)還想說用recursive 來寫(!)
搞個return array 就快史惹bar  XD 

雖然感覺到跟queue 有關係,但沒有想到可以用index 來當做放進去queue的東西!!!
為什麼別人總是那麼聰明 QQ
因為覺得queue的超過buffer 很麻煩,不喜歡跑回前面,也不喜歡一次宣告超大queue XD
就用我(自以為)很熟的 linked list 來解決queue的問題!有head 有tail,是一個dequeue跟 enqueue的很快的東西(我覺得)反正就是醬(丟筆)

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
struct Node{
int val;
struct Node* next;
};

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

int* deckRevealedIncreasing(int* deck, int deckSize, int* returnSize) {
int *ret = calloc (deckSize, sizeof(int));
*returnSize = deckSize;
qsort (deck, deckSize, sizeof(int), comp);
//create queue
struct Node *head = NULL;
struct Node *tail, *ptr;
for (int i=0; i<deckSize; i++)
{
struct Node *ptr = calloc (1, sizeof(struct Node));
ptr->val = i;
ptr->next = NULL;
if (head == NULL)
head = ptr;
else
tail->next = ptr;
tail = ptr;
}
int count = 0;
ptr = head;
while (ptr != NULL)
{
//dequeue , put to ret
int idx = ptr->val;
ret[idx] = deck[count++];
ptr = ptr->next;
head->next = NULL;
free(head);
if (ptr == NULL)
break;
head = ptr;
//enqueue to tail
tail->next = head;
tail = tail->next;
ptr = ptr->next;
head->next= NULL;
head = ptr;
}
return ret;
}

沒有留言:

張貼留言