給定一個順序存儲的線性表,請設計一個算法查找該線性表中最長的連續遞增子序列。例如,(1,9,2,5,7,3,4,6,8,0)中最長的遞增子序列為(3,4,6,8)。
輸入格式:
輸入第1行給出正整數n(≤105);第2行給出n個整數,其間以空格分隔。
輸出格式:
在一行中輸出第一次出現的最長連續遞增子序列,數字之間用空格分隔,序列結尾不能有多余空格。
輸入樣例:
-
15
-
1 9 2 5 7 3 4 6 8 0 11 15 17 17 10
輸出樣例:
3 4 6 8
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader sr = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(sr.readLine());
int[] res=new int[n];
String s[] = sr.readLine().split(" ");
for(int i=0;i<n;i++)
res[i]=Integer.parseInt(s[i]);
int max=0,count=0,ss=0,x=0,y=0;
for(int i=0;i<n-1;i++) {
y=i+1;//判斷是否遞增,是的話count++;
if(res[i+1]>res[i]) {
count++;
if(count>max) {
max=count;
ss=x;
}
}else {
count=0;
x=y;//不連續遞增,則索引改變為下一個目標
}
}
for(int i=ss;i<=ss+max;i++) {
if(i==(ss+max)) {
System.out.print(res[i]);
}else {
System.out.print(res[i]+" ");
}
}
}
}
實現二:
public class Sample {
public static void main(String[] args) {
int []nums = {1,3,4,5,6,7,2,8,9,10};
for (int[] lu : findAllLowUpIndex(nums)) {
System.out.printf("下標:%d, 上標:%d, 長度%d\n", lu[0], lu[1], lu[1]-lu[0]);
}
}
public static List<int[]> findAllLowUpIndex(int[] nums) {
Map<Integer, int[]> map = new HashMap<>(); //map的key是長度,value是數組的上下標
for (int i=0, j=0; i<nums.length-1; i++) {
for (j=i+1; j<nums.length && nums[j-1]<nums[j]; j++) {
map.put(j-i, new int[] {i, j}); //j-i就是長度,i是下標,j是上標,相同長度的返回較大的index,所以后來的index直接覆蓋之前的信息
}
}
return map.entrySet().stream()
.sorted((e1,e2)->e1.getKey().compareTo(e2.getKey())) //這里是為了按長度排序
.map(e->e.getValue()).collect(Collectors.toList()); //這里是去掉長度信息只保留上下標信息
}
}
實現三:
public class Test3 {
public static void main(String[] args) {
int[] nums = new int[]{5, 6, 7, 0,
1, 2, 3, 8, 4, 5, 7, 9, 21};
calc(nums);
}
public static void calc(int[] nums) {
int[] max = null;
int start = 0;
int end = 0;
for (int i = 1; i < nums.length; i++) {
int pre = nums[i - 1];
int cur = nums[i];
if (cur > pre) {
end = i;
}
if (cur <= pre || i == nums.length - 1) {
if (max == null || max[1] - max[0] <= end - start) {
max = new int[]{start, end};
}
start = i;
}
}
System.out.println(String.format("[%s,%s]", max[0], max[1]));
}
}
實現四:
public class Sample {
public static void main(String[] args) {
int []nums = {1,3,4,5,6,7,2,8,9,10,3,4,5,6,7,1,8,6,5};
for (int[] lu : findAllLowUpIndex(nums)) {
System.out.printf("y:%d=>%d\n", lu[0], lu[1]);
}
}
public static List<int[]> findAllLowUpIndex(int[] nums) {
List<int[]> result = new ArrayList<>();
for (int i=0, j=0; i<nums.length-1; i=j) {
for (j=i+1; j<nums.length && nums[j-1]<nums[j]; j++);
if (j-1>i) { //長度為2以上則保存結果
result.add(new int[] {i, j-1});
}
}
return result;
}
}
