问题:
一副含有1到n的牌组成的牌堆,不知道顺序,每次从牌堆顶取一张放桌子上(从左到右平铺),再取一张放牌堆底,直到牌堆没牌,最后桌子上的牌是从1到n有序,设计程序,输入n,输出牌堆的顺序数组
思路:
该题2个数组元素集合相同,顺序不同,可以看做2个数组下标一 一对应交换。我们可以模拟长度n的输入数组按题操作,取得输出数组,然后查看2个数组中同值的下标关系,来取得输入与输出的映射关系。
最后按照映射关系还原输入数组即可。
代码思路:
- 按照输入n,取得顺序输出数组newDeck[1,2,3…n];
- 复制该数组到一个arraylist上作为input,再新建一个arraylist作为output,以便模拟抽放牌过程。
抽牌放桌上就是 input抽一张放入output的牌组,input随即删除一张牌顶牌
然后检查input是否还有牌,有则input牌底放一张牌顶的牌,牌顶随后删除
循环直至output牌满n张或者input无牌(此时output放的就是newDeck为输入的输出牌组) - 设输入牌组是oldDeck,长度n,准备还原;
- 遍历newDeck的牌,每张依次和output中的牌比较,如果发现相同的牌,取得两个下标关系(输入下标和输出下标),然后,按照关系将设为输出时的newDeck依次还原,即newDeck[输出下标]还原给oldDeck[输入下标],
- 完成newDeck遍历时,即每个数都被还原到oldDeck,输出oldDeck即可
java代码:
public static void restoreDeck(int n){
/*
*deck output as described
*/
Integer[] newDeck = new Integer[n];
for(int i=0;i<n;i++){
newDeck[i] = i+1;
}
/*
*use the output deck as an example of input to get the example of output
*/
var exampleInput = new ArrayList<Integer>(Arrays.asList(newDeck));
var exampleOutput = new ArrayList<Integer>();
while(exampleInput.size() > 0){
exampleOutput.add(exampleInput.get(0));
exampleInput.remove(0);
if(exampleInput.size() > 0){
exampleInput.add(exampleInput.get(0));
exampleInput.remove(0);
}
}
/*
*return the newDeck elements back to oldDeck
*/
int[] oldDeck = new int[n];
for (int i=0;i<n;i++){
for(int j=0;j<exampleOutput.size();j++){
if (newDeck[i]==exampleOutput.get(j)){
oldDeck[i] = newDeck[j];
}
}
}
System.out.println(Arrays.toString(oldDeck));
}
测试:
public static void main(String[] args) {
restoreDeck(1);
restoreDeck(2);
restoreDeck(3);
restoreDeck(4);
restoreDeck(5);
restoreDeck(6);
}
输出:
[1]
[1, 2]
[1, 3, 2]
[1, 3, 2, 4]
[1, 5, 2, 4, 3]
[1, 4, 2, 6, 3, 5]