题解 | #MP3光标位置#

MP3光标位置

https://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15

看题解写得都花里胡哨的,实际上只需要维护两个变量,cur指向当前选择,top指向当前列表顶部,两者关系cur - top < 4,只需要在up和down的时候注意下两者关系就行了
import java.io.IOException;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());
        char[] commands = scanner.nextLine().toCharArray();

        int top = 1;
        int cur = 1;
        for (char command : commands) {
            switch (command) {
                case 'U':
                    if (cur == 1) {
                        cur = n;
                        if (cur > 4) {
                            top = cur - 3;
                        } else {
                            top = 1;
                        }
                    } else {
                        cur--;
                        if (top > cur) {
                            top = cur;
                        }
                    }
                    break;
                case 'D':
                    if (cur == n) {
                        top = cur = 1;
                    } else {
                        cur++;
                        if (cur > top + 3) {
                            top++;
                        }
                    }
                    break;
            }
        }
        int max = Math.min(top + 3, n);
        for (int i = top; i <= max; i++) {
            System.out.print(i);
            if (i != max) {
                System.out.print(" ");
            }
        }
        System.out.println();
        System.out.println(cur);
    }

}


全部评论

相关推荐

06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
06-23 11:43
门头沟学院 Java
allin校招的烤冷...:我靠,今天中午我也是这个hr隔一个星期发消息给我。问的问题还是一模一样的😅
点赞 评论 收藏
分享
评论
4
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务