正在处理 LeetCode 问题 950: 这个想法是找到卡片的顺序,其中抽出的卡片将按递增顺序排列,但在每抽出一张卡片之后,下一张卡片就会放在底部。
class Solution {
public int[] deckRevealedIncreasing(int[] deck) {
Arrays.sort(deck);
Queue<Integer> part_1 = new LinkedList<>();
Queue<Integer> part_2 = new LinkedList<>();
int i=0;
for(; i<deck.length/2+1; i++){ part_1.add(deck[i]);}
for(; i<deck.length; i++){ part_2.add(deck[i]);}
//Here is where the problem is, An error arises saying I'm accessing an empty Queue
// but as you can see, every time I remove an element I'm adding it to the end.
// Therefore the queue should never be empty.
for(int j=0; j<part_1.size(); j++){
int temp = part_2.poll();
part_2.add(temp);
}
int[] rec = new int[deck.length];
for(int r = 0; r<rec.length; r++){
if(r%2==0) {rec[r]=part_1.poll(); }
else if(!part_2.isEmpty()){ rec[r] = part_2.poll(); }
}
return rec;
}
}
如果您的参数
deck
只有 1 个元素,则该元素将存储在您的列表 part_1
中,并且 part_2
将为空。在这种情况下,您应该收到队列为空的错误。