iT邦幫忙

2024 iThome 鐵人賽

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

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

Day12__C語言刷LeetCode

  • 分享至 

  • xImage
  •  

961. N-Repeated Element in Size 2N Array

tags: Easy、Sizeof

You are given an integer array nums with the following properties:
nums.length == 2 * n.
nums contains n + 1 unique elements.
Exactly one element of nums is repeated n times.
Return the element that is repeated n times.

解法1: 雙重for 迴圈

int repeatedNTimes(int* nums, int numsSize) {
    int temp;
    int n = numsSize / 2;

    for (int i = 0; i < numsSize; i++) {
        int count = 0;
        for (int j = 0; j < numsSize; j++) {
            if (nums[i] == nums[j]) {
                count++;
                if (count >= 2) {
                    temp = nums[i];
                    break;
                }
            }
        }
    }
    return temp;
}

解法2: HashTable

int repeatedNTimes(int* nums, int numsSize) {
    int hashtable[10000] = {0};
    for (int i = 0; i < numsSize; i++) {
        if (hashtable[nums[i]] == 1) {
           return nums[i];
        }
        hashtable[nums[i]] = 1;
    }
    return 0;
}

2138. Divide a String Into Groups of Size k

tags: Easy、sizeof

A string s can be partitioned into groups of size k using the following procedure:
The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.
For the last group, if the string does not have k characters remaining, a character fill is used to complete the group.
Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s.
Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.

解法:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** divideString(char* s, int k, char fill, int* returnSize) {
    int length = strlen(s);
    int result_size = (length + k - 1) / k;

    char** result = (char**)malloc(result_size * sizeof(char*));

    for (int i = 0; i < result_size; i++) {
        result[i] = (char*)malloc((k+1) * sizeof(char));
        for (int j = 0; j < k; j++) {
            int index = i * k + j;
            if (index < length) {
                result[i][j] = s[index];
            }
            else {
                result[i][j] = fill;
            }
        }
        result[i][k] = '\0';
    } 
    *returnSize = result_size;
    return result;
}

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

尚未有邦友留言

立即登入留言