我有一個array
的int
作爲輸入。數組總是長度爲2^n
。我想把數組切成兩半並堆疊起來。重複切割和堆疊,直到只有一個堆疊。例如:切割和堆疊陣列
int[] array = {1,2,3,4,5,6,7,8}
如果我們削減了一半的陣列,我們和堆棧他們來說,這將是:
{1,2,| 3,4}
{5,6,| 7,8}
切割並重新堆棧:再次
{1,|2}
{5,|6}
{3,|4}
{7,|8}
:
{1}
{5}
{3}
{7}
{2}
{6}
{4}
{8}
所需的輸出將是整數的數組從頂部到堆棧
int[] output = {1,5,3,7,2,6,4,8}
我曾嘗試通過循環輸入數組以特定的方式來構造輸出數組的末尾。請注意,當我到達陣列時,我只是再次從頭開始。我從array[i]
開始,其中i = 0
。我以這種方式得到第一個數字。那麼我增加i
n,其中n
是log(array.legnth)
(基數2)。這是我如何得到第二個數字。對於第三個數字,我們增加i
(n + n/2)。對於第四個數字,我們再次增加i
n
。我想知道有沒有一種模式?或者你會怎樣解決這個問題?我正在尋找java或python中的解決方案。
編輯/更新:
我試圖用queue
一種新的方法。我基本上保持切割數組的一半,並將數組的一半推入隊列,直到隊列中的數組全部長度爲2(或堆棧高度爲n)。但我的結果是不正確的。我認爲它與我將半數組添加回隊列的順序有關。
import java.util.*;
public class StackArray{
public static void main(String[] args){
int[] array = {1,2,3,4,5,6,7,8};
int[] answer = stackArray(array);
for(int n : answer){
System.out.println(n);
}
}
public static int[] stackArray(int[] array){
int height = (int) (Math.log(array.length)/Math.log(2)) + 1;
Queue<int[]> queue = new LinkedList<int[]>();
ArrayList<Integer> list = new ArrayList<>();
queue.add(array);
while(queue.size() < height){
int currentLength = queue.size();
int i = 0;
while(i < currentLength){
int[] temp = queue.poll();
int[] array1 = new int[temp.length/2];
int[] array2 = new int[temp.length/2];
System.arraycopy(temp, 0, array1, 0, array1.length);
System.arraycopy(temp, array1.length, array2, 0, array2.length);
queue.add(array1); //I think the problem is here
queue.add(array2);
i++;
}
}
int y = 0;
while(y < 2){
for(int i = 0; i < queue.size(); i++){
int[] curr = queue.poll();
list.add(curr[y]);
queue.add(curr);
}
y++;
}
int[] ret = new int[list.size()];
for(int i = 0; i < list.size(); i++){
ret[i] =list.get(i);
}
return ret;
}
}
結果:
1
3
5
7
2
4
6
8
我將如何解決這一問題?
更新:我解決了它,並張貼了我自己的答案。但我仍然很好奇,其他人如何解決這個問題。請隨時回答。
請選擇一個* *語言。然後編輯您的問題以將該語言作爲標記,並且還包括您已經嘗試過的[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)以及對它的描述沒有按預期工作。如果你最近沒有做過,那麼請花一些時間再讀一遍[閱讀如何提出好問題](http://stackoverflow.com/help/how-to-ask)。 –