iT邦幫忙

2024 iThome 鐵人賽

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

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

Day09__C語言刷LeetCode

  • 分享至 

  • xImage
  •  

2833. Furthest Point From Origin

tags: Easy、Pointer

You are given a string moves of length n consisting only of characters 'L', 'R', and ''. The string represents your movement on a number line starting from the origin 0.
In the ith move, you can choose one of the following directions:
move to the left if moves[i] = 'L' or moves[i] = '
'
move to the right if moves[i] = 'R' or moves[i] = '_'
Return the distance from the origin of the furthest point you can get to after n moves.

解法:

#define absolute(a) ((a) > 0 ? (a) : (-a)) //使用define更能節省空間

int furthestDistanceFromOrigin(char * moves) {
    int left_dis = 0;
    int right_dis = 0;
    int free_dis = 0;
    int max_dis = 0;

    for (int i = 0; moves[i] != '\0'; i++) {
        if (moves[i] == 'L') {
            left_dis++;
        }
        else if (moves[i] == 'R') {
            right_dis++;
        }
        else if (moves[i] == '_'){
            free_dis++;
        }
    }
    left_dis -= right_dis;
    max_dis = absolute(left_dis) + free_dis;
    return max_dis;
}

1266. Minimum Time Visiting All Points

tags: Easy、Pointer

On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.
You can move according to these rules:
In 1 second, you can either:
move vertically by one unit,
move horizontally by one unit, or
move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).
You have to visit the points in the same order as they appear in the array.
You are allowed to pass through points that appear later in the order, but these do not count as visits.

解法:

#define absolute(a) ((a) > 0 ? (a) : (-a))
int minTimeToVisitAllPoints(int** points, int pointsSize, int* pointsColSize) {
    int min_time = 0;

    for (int i = 0; i < pointsSize-1; i++) {
        int diffX = absolute((points[i+1][0] - points[i][0]));
        int diffY = absolute((points[i+1][1] - points[i][1]));
        min_time += diffX > diffY ? diffX : diffY;
    }
    return min_time;
}

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

尚未有邦友留言

立即登入留言