iT邦幫忙

2024 iThome 鐵人賽

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

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

Day10__C語言刷LeetCode

  • 分享至 

  • xImage
  •  

2848. Points That Intersect With Cars

tags: Easy、Pointer

You are given a 0-indexed 2D integer array nums representing the coordinates of the cars parking on a number line. For any index i, nums[i] = [starti, endi] where starti is the starting point of the ith car and endi is the ending point of the ith car.
Return the number of integer points on the line that are covered with any part of a car.

解法1: 用bool

int numberOfPoints(int** nums, int numsSize, int* numsColSize){
    bool covered[101] = {false};
    int count = 0;

    for (int i = 0; i < numsSize; i++) {
        int start = nums[i][0];
        int end = nums[i][1];

        for (int j = start; j <= end; j++) {
            if (!covered[j]) {
                covered[j] = true;
                count++;
            }
        }
    }
    return count;
}

解法2:用數值計算

int numberOfPoints(int** nums, int numsSize, int* numsColSize){
    int park[101] = {0};
    int count = 0;

    for (int i = 0; i < numsSize; i++) {
        int start = nums[i][0];
        int end = nums[i][1];
        for (int j = nums[i][0]; j <= nums[i][1]; j++) {
            park[j] += 1;
        }
    }
    for (int i = 0; i < 101; i++) {
        if (park[i] > 0) {
            count++;
        }
    }

    *numsColSize = count;
    return count;
}

1637. Widest Vertical Area Between Two Points Containing No Points

tags: Easy、Point

Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area.
A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.
Note that points on the edge of a vertical area are not considered included in the area.

解法:

int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}
int maxWidthOfVerticalArea(int** points, int pointsSize, int* pointsColSize) {
    int max = 0;
    int *arr = malloc(pointsSize * sizeof(int));
    for (int i = 0; i < pointsSize; i++) {
        arr[i] = points[i][0];
    }
    qsort(arr, pointsSize, sizeof(int), compare);
    for(int i = 0; i < pointsSize-1; i++) {
        int diff = arr[i+1] - arr[i];
        if (diff > max) {
            max = diff;
        }
    }
    
    *pointsColSize = max;
    return max;

}

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

尚未有邦友留言

立即登入留言