classSolution { publicintpassThePillow(int n, int time) { intans=1, k = 1; while (time-- > 0) { ans += k; if (ans == 1 || ans == n) { k *= -1; } } return ans; } }
时间复杂度:$O(time)$
空间复杂度:$O(1)$
方法二:数学
1 2 3 4 5 6 7
classSolution { publicintpassThePillow(int n, int time) { intk= time / (n - 1); intmod= time % (n - 1); return (k & 1) == 1 ? n - mod : mod + 1; } }