输入n个数,找到这n个数中连续递增的序列
输入n个数,找到这n个数中连续递增的序列
一、使用蛮力法完成题目
问题描述:输入n个数,找到这n个数中连续递增的序列。
输入:n个数
输出:递增序列
例如:输入:12、 3、 4 、6、 9、 1、15、14、20、21、22
输出:3、4
20、21
21、22
20、21、22
二、代码与测试结果
1 方法一
此方法是输出连续递增序列的最大序列不合题意
package com.算法设计与分析报告题目;
import java.util.Arrays;
import java.util.Scanner;
public class text3 {
//问题描述:输入n个数,找到这n个数中连续递增的序列。
//找到连续递增数组并输出
static void printArray(int[] a) {
int j = 1;
int i = 1;
String s = "";
s = a[0] + " ";
while (i < a.length) {
if (a[i - 1] == a[i] - 1) {
s += (a[i] + " ");
i++;
j++;
} else {
if (j != 1) {
System.out.println(s);
j=1;
}
i++;
s = a[i - 1] + " ";
}
}
if(j != 1 ){
System.out.println(s);
}
}
public static void main(String[] args) {
int l,x;
System.out.println("班级^^^^^%………………");
System.out.print("请输入数组的长度:");
Scanner sc = new Scanner(System.in);
l =sc.nextInt();
int []a = new int[l];
for(int i = 0; i < l; i++ ){
System.out.print("请输入数组的第"+ (i+1) +"个数:");
x = sc.nextInt();
a[i] = x;
}
System.out.print("你输入的数组位:");
System.out.println(Arrays.toString(a));
// int[] a = { 12, 3, 4 ,6, 9, 1,15,14,20,21,22};
System.out.println("找到的连续递增数组有以下");
text3.printArray(a);
}
}
1.1 方法一的输出结果
2 方法二
下列代码是,根据方法一的基础上改,实现了题目要求,并目前为发现错误
package com.算法设计与分析报告题目;
import java.util.Arrays;
import java.util.Scanner;
public class text3_2 {
//问题描述:输入n个数,找到这n个数中连续递增的序列。
//找到连续递增数组并输出
static void printArray(int[] a) {
int i = 1; //i为数组下标
int j = 1; //j为,s字符串的下标
int k = 1; //k 为记字符串的长度
String s = ""; //输出的结果s
s = a[0] + " "; //
while (i < a.length) {
//判断这个数组跟上一个数组是否连续,且判断的数不是最后一个
if (k != a.length && a[k - 1] == a[k] - 1) {
s += (a[k] + " ");
k++;
j++;
System.out.println(s);
} else{ //否则原数组右移一位
i++;
k = i;
s = (a[k - 1] + " ");
j=1;
}
}
if(j != 1 ){ //是否有最后一个连续递增数组
System.out.println(s);
}
}
public static void main(String[] args) {
int l,x; //l为输入数组的长度,x 为输入的数组值
System.out.println("班级:6^^^^^^^^………………");
System.out.print("请输入数组的长度:");
Scanner sc = new Scanner(System.in);
l =sc.nextInt();
int []a = new int[l];
for(int i = 0; i < l; i++ ){ //一个一个输入数组的数
System.out.print("请输入数组的第"+ (i+1) +"个数:");
x = sc.nextInt();
a[i] = x;
}
System.out.print("你输入的数组位:");
System.out.println(Arrays.toString(a)); //遍历输入的数组
System.out.println("找到的连续递增数组有以下");
text3_2.printArray(a); //调用方法
}
}