样本输入:
8 //数组大小
3 4 5 7 8 9 4 3 //电压
样本输出:
6 // 9-3 [9是峰值电压,3是起始点]
这是我写的代码:
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
scan.nextLine();
String input = scan.nextLine();
String[] s = input.split(" ");
List <Integer> list = new ArrayList<Integer>();
for(int i=0 ; i<size ; i++)
{
list.add(Integer.parseInt(s[i]));
}
list.sort(Collections.reverseOrder());
System.out.println(list.get(0)-list.get(list.size()-1));
//System.out.println("LAST : " +list.get(0)+"FIRST :"+list.get(list.size()-1));
}
}
但这仅适用于单个峰。 但是,如果输入类似:
12 //数组大小
1 2 3 4 2 1 -1 0 2 7 5 4 //电压
答案应该是
第一刺:
Start Point = 1
Peak Point = 4
Spike height = 4 - 1 = 3.
秒杀:
Start Point = -1
Peak Point = 7
Spike height = 7 - (-1) = 8.
我尝试将列表分为两个列表,每个部分都有自己的峰值。
我正在寻找可以发现任何数量的尖峰的解决方案。
谢谢!!
编辑:--------
int temp = 0;
int count = 0;
int foo = 0;
for(int i=0 ; i<list.size()-1 ; i++)
{
temp = list.get(i);
if(list.get(i+1)-temp == 1)
{
count++;
}
else
{
foo++;
}
}
我尝试了上面的方法,使用count和foo作为list的索引:
System.out.println(list.get(count)-list.get(0));
System.out.println(list.get((count)+foo)-list.get(foo));