Java數組參數應用&輸出數組遞增數列"以輸出最長數組遞增數列實驗爲例"

Q14.
Write a method called longestSortedSequence that accepts an
array of integers as a parameter and that returns the length of
the longest sorted (nondecreasing) sequence of integers in the array
Q14.
此實驗要求利用一個整數數組作爲參數,並且輸出數組中最長
且有序的(非遞減)的數列。
以{3,2,1,0,1,5,4,5,6,7,8,0}爲例(輸入數組方法已經標註)

import java.util.*;
import java.util.Scanner;
public class Q14 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner console = new Scanner (System.in);
		/*System.out.println("Type the length for array num: ");
		int length = console.nextInt();
		int[]num = new int[length];
		for (int i=0;i<num.length;i++) {
			System.out.println("Type the #"+(i+1)+" for array");
			num[i]=console.nextInt();
		}
		//輸入數組
		*/
		int []num = {3,2,1,0,1,5,4,5,6,7,8,0};
		//樣本數組 {3,2,1,0,1,5,4,5,6,7,8,0}
		int []longest = longestSortedSequence(num);
		System.out.println(Arrays.toString(longest));
	}
	public static int[] longestSortedSequence(int[]a1) {
		
		int max =1;
		//記錄最長遞增數列的長度
		int count =1;
		//與max值進行比較
		int longestpoint =0;
		//longestpoint記錄數組中最長序列的位號
		for (int i=1;i<a1.length;i++) {
			if(a1[i]>a1[i-1]) {
				count++;
			}else if(a1[i]<=a1[i-1]&&count>max){
				max =count;
				longestpoint = i-1;
				//記錄最長位號
				count=1;
				//count迴歸起初值1
			}
		}
	/*	System.out.print(max);
		System.out.print(count);
		System.out.print(longestpoint);*/
		//檢驗上述調整準確性,本實驗中應輸出5110
		int []result = new int[max];
		for (int a=max-1;a>=0;a--) {
			result[a]= a1[longestpoint+(a+1-max)];
			//從最後一位最大的數開始回步取值
		}
		return result;
	}
}

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