Java数组参数应用&输出数组递增数列"以输出最长数组递增数列实验为例"

mac2026-03-28  3

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; } }
最新回复(0)