M-223.小S的超辣火锅挑战
思路
索引引模运算的数组头尾循环 + 指定循环次数下的特殊操作
代码(数组头尾循环做法)
import java.util.Arrays;
public class Main {
public static int[] solution(int n, int k, int[] a) {
// PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
// write code here
// 一个非常简单的数组循环问题
// 解题思路:取用原数组a[],对a[]进行循环,循环终止条件是离席人数到n
// 每次循环到对应的人,我们对其耐受值-1,如果这个人的耐受值为0,则出局
// 在循环过程中,对遇见到的出局的人跳过,通过“索引模运算”的方式对数组进行头尾循环遍历
int[] out = new int[n];
int outTotal = 0;
int index = 0;
int count = 0;
while (outTotal != n) {
if (a[index] > 0) {
if ((count + 1) % k == 0) {
a[index] -= 1;
if (a[index] == 0) {
out[outTotal] = index + 1;
outTotal += 1;
}
}
count++; // 当且仅当是循环到的人是“未出局”的人时才会计数
} else {
// 此处代码为空,跳过“已出局的人”
}
index = (index + 1) % n; //无论是否是否出局,都需要更新索引
}
return out;
}
public static void main(String[] args) {
System.out.println(Arrays.equals(solution(5, 2, new int[]{1, 4, 2, 9, 4}), new int[]{1, 3, 5, 4, 2}));
System.out.println(Arrays.equals(solution(3, 2, new int[]{1, 2, 3}), new int[]{1, 3, 2}));
System.out.println(Arrays.equals(solution(4, 3, new int[]{3, 1, 2, 1}), new int[]{2, 1, 3, 4}));
System.out.println(Arrays.equals(solution(5, 1, new int[]{2, 2, 3, 1, 2}), new int[]{4, 1, 2, 5, 3}));
}
}
代码(双端队列左旋k-1次作法)
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public class Main {
public static int[] solution(int n, int k, int[] a) {
// PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
// write code here
class Node {
int id;
int patience;
Node (int id, int patience) {
this.id = id;
this.patience = patience;
}
}
Deque<Node> dq = new ArrayDeque<>();
// 初始化队列
for (int i = 0; i < n; i++) {
dq.offerLast(new Node(i + 1, a[i]));
}
int[] out = new int[n];
int outTotal = 0;
while (!dq.isEmpty()) {
// 左旋队列k-1次,以模拟顺时针数k个
for (int i = 0; i < k-1; i++) {
Node rotate = dq.pollFirst();
dq.offerLast(rotate);
}
Node now = dq.pollFirst();
now.patience -= 1;
if (now.patience > 0) {
dq.offerLast(now);
} else if (now.patience == 0) {
out[outTotal] = now.id;
outTotal+=1;
}
}
return out;
}
public static void main(String[] args) {
System.out.println(Arrays.equals(solution(5, 2, new int[]{1, 4, 2, 9, 4}), new int[]{1, 3, 5, 4, 2}));
System.out.println(Arrays.equals(solution(3, 2, new int[]{1, 2, 3}), new int[]{1, 3, 2}));
System.out.println(Arrays.equals(solution(4, 3, new int[]{3, 1, 2, 1}), new int[]{2, 1, 3, 4}));
System.out.println(Arrays.equals(solution(5, 1, new int[]{2, 2, 3, 1, 2}), new int[]{4, 1, 2, 5, 3}));
}
}