欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 【无标题】

【无标题】

2025/3/16 12:33:57 来源:https://blog.csdn.net/wang__12300/article/details/146286669  浏览:    关键词:【无标题】

学习记录

2025.3.15

题目:

在这里插入图片描述

思路:按照题目对i,j进行加减。

解题步骤:

1。 变量初始化:i 和 j 初始值都为 0。它们将根据命令进行更新。
2.遍历命令。
3. 处理每个命令:s.charAt(0) 获取当前命令字符串的第一个字符,用于判断命令类型。switch 语句根据命令的第一个字符来决定如何更新 i 和 j:
‘U’:i 减 1(向上移动)。‘D’:i 加 1(向下移动)。‘L’:j 减 1(向左移动)。默认情况(即其他字符):j 加 1(向右移动)。
4. 返回结果。

代码:

int finalPositionOfSnake(int n, char** commands, int commandsSize) {int ans = 0;for (int i = 0; i < commandsSize; i++) {if (commands[i][0] == 'U') {ans -= n;} else if (commands[i][0] == 'D') {ans += n;} else if (commands[i][0] == 'L') {ans--;} else {ans++;}}return ans;
}
class Solution {public int finalPositionOfSnake(int n, List<String> commands) {int i = 0;int j = 0;for (String s : commands) {switch (s.charAt(0)) {case 'U' -> i--;case 'D' -> i++;case 'L' -> j--;default  -> j++;}}return i * n + j;}
}

复杂度:

N(N)
N(1)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词