题解 | #MP3光标位置#
MP3光标位置
https://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15
针对题目描述,实际上就是要维护一个滑动窗口,大小为Math.min(songs, 4);
忽略0位置,从1到n方便计数,start = 1, end = Math.min(songs, 4),cur保存当前位置;
每次根据操作为U则加一,反之减一,会出现两种情况,超过窗口或没超过,通过!(start <= cur && cur <= end)判断;
针对U操作来分析,如果cur不越过位置1,那么每次向上挪动时,窗口左边界start变成cur,右边界变为左边界+窗口大小-1;
如果越过1,观察发现右边界变成cur的位置,而左边界变成了右边界-窗口大小+1;
因为每次取余,会出现特殊情况,cur为1向上挪动时变成0,cur为n-1向下挪动变成n,前者被特殊处理了,而后者则需要加个判断,不然会跳出窗口出现值为0的情况。
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextInt()) { // 注意 while 处理多个 case int songs = in.nextInt(); String oper = in.next(); int start = 1, end = Math.min(songs, 4), cur = 1; int window = Math.min(songs, 4) -1; for (int i = 1; i <= oper.length(); i++) { if (oper.charAt(i - 1) == 'U') { cur = cur - 1; if (!(start <= cur && cur <= end)) { if (start == 1) { cur = songs; end = cur; start = end - window; } else { cur = cur % songs; start = cur; end = start + window; } } } else { cur = cur + 1; if (!(start <= cur && cur <= end)) { if (end == songs) { cur = 1; start = cur; end = start + window; } else { cur = cur == songs ? songs : cur % songs; end = cur; start = end - window; } } } } StringBuilder sb = new StringBuilder(); while (start <= end) { sb.append(start + " "); start++; } System.out.println(sb.toString()); System.out.println(cur); } } }