網易筆試題:數組轉置問題

問題:

小易有一個長度爲n的整數序列,a_1,...,a_n。然後考慮在一個空序列b上進行n次以下操作:
1、將a_i放入b序列的末尾
2、逆置b序列
小易需要你計算輸出操作n次之後的b序列。 


思路:輸入4個數,分別爲1,2,3,4;查找規律。

(1)輸入1,結果爲1

(2)輸入2,隊列1,2;轉置後結果爲2,1

(3)輸入3,隊列3,1,2;此時不需要轉置,因爲結果3,1,2

(4)輸入4,隊列3,1,2,4;此時需要轉置,結果爲4,2,1,3

根據以上規律,可以看出,每當輸入一個數時,需要將此數放在對頭或對尾(n-1個放在對頭,n個放在對尾),一個需要轉置,另一個不需要轉置。

import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;

import javax.sound.midi.Sequence;

public class Main {
	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int[] num=new int[n];
		boolean convert=false;
		for(int i=0;i<n;i++){
			num[i]=sc.nextInt();
		}
		Deque<Integer> que=new LinkedList<Integer>();
		for(int k=0;k<n;k++){
			if(convert){
				que.addLast(num[k]);
			}else{
				que.addFirst(num[k]);
			}
			convert=!convert;
		}
		
		if(convert){
			while(que.size()!=1){
				System.out.print(que.pollFirst()+" ");
			}
			System.out.print(que.pollFirst());
		}else{
			while(que.size()!=1){
				System.out.print(que.pollLast()+" ");
			}
			System.out.print(que.pollLast());
		}
		
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章