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;
}
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;
}