iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0
佛心分享-刷題不只是刷題

C/C++ 刷題30天系列 第 6

Day06__C語言刷LeetCode

  • 分享至 

  • xImage
  •  

83. Remove Duplicates from Sorted List

tags: Easy、Linked List

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

解法:

struct ListNode* deleteDuplicates(struct ListNode* head) {
    struct ListNode *current = head;

    while (current != NULL && current->next != NULL) {
        if (current->val == current->next->val) {
            struct ListNode *temp = current->next;
            current->next = current->next->next;
            free(temp);
        }
        else {
            current = current->next;
        }
    }
    return head;
}

1313. Decompress Run-Length Encoded List

tags: Easy、Array

We are given a list nums of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements [freq, val] = [nums[2i], nums[2i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.
Return the decompressed list.

解法:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* decompressRLElist(int* nums, int numsSize, int* returnSize) {
    int totalSize = 0;
    for (int i = 0; i < numsSize; i += 2) {
        totalSize += nums[i];
    }

    int* decompressedList = (int*)malloc(totalSize * sizeof(int));

    int index = 0;
    for (int i = 0; i < numsSize; i += 2) {
        int freq = nums[i];
        int val = nums[i+1];
        for (int j = 0; j < freq; j++) {
            decompressedList[index++] = val;
        }
    }
    *returnSize = totalSize;
    return decompressedList;
}

上一篇
Day05__C語言刷LeetCode
下一篇
Day07__C語言刷LeetCode
系列文
C/C++ 刷題30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言