持续更新,等待交流,,,如有错误请提出交流,更正
************************************【第一题:数组中的最长山谷】***************************************
方法一:堆栈
package pinduoduo;
import java.util.Scanner;
import java.util.Stack;
public class MountainValley {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<Integer> s1 = new Stack<>();//左坡
Stack<Integer> s2 = new Stack<>();//右坡
int max = Integer.MIN_VALUE;
while (sc.hasNext()) {
while (sc.hasNext()) {
int a = sc.nextInt();
if (s1.isEmpty()) {
s1.push(a);
} else {
if (a < s1.peek()) {
s1.push(a);
} else {
s2.push(a);
break;
}
}
}
int b = Integer.MAX_VALUE; //存储山谷后的一个值
while (sc.hasNext()) {
int a = sc.nextInt();
if (s2.isEmpty()) {
s2.push(a);
} else {
if (a > s2.peek()) {
s2.push(a);
} else {
b = a;
break;
}
}
}
if (s1.size() > 1 && s2.size() > 0) {
if (max < s1.size() + s2.size()) {
max = s1.size() + s2.size();
}
s1.clear();
s1.push(s2.peek());
if (b != Integer.MAX_VALUE) {
s1.push(b);
}
s2.clear();
} else {
s1.clear();
if (!s2.isEmpty()) {
s1.push(s2.peek());
if (b != Integer.MAX_VALUE) {
s1.push(b);
}
s2.clear();
}
}
}
System.out.println(max);
}
}
方法二:直接法
public static int longestMountain(int[] A) {
int res = 0, up = 0, down = 0;
for (int i = 1; i < A.length; ++i) {
if (up > 0 && A[i - 1] > A[i] || A[i - 1] == A[i])
up = down = 0;
if (A[i - 1] < A[i])
up++;
if (A[i - 1] > A[i])
down++;
if (up > 0 && down > 0 && up + down + 1 > res)
res = up + down + 1;
}
return res;
}
*************************************【第二题:二维生物】************************************************
package pinduoduo;
import java.util.Scanner;
//二维生物
public class TwoDimenBiology {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long target = Math.abs(sc.nextLong());
long sum = 0;
long step = 1;// 步长
while (sum < target) {// 查找超过去的sum
sum += step;
step++;
}
step--;
if (sum == target) {
System.out.println(step);
} else {
step += (sum - target) * 2;// 向前+向后=sum-1,一共(sum-target)*2次
System.out.println(step);
}
}
}
*************************************【第三题:字符串构造】************************************************
package pinduoduo;
import java.util.Scanner;
//字符串构造
public class StrMake {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(make(s));
}
public static String make(String s) {
for (int i = 1; i < s.length(); i++) {
String str = s.substring(0, i);
StringBuffer sb = new StringBuffer();
for (int j = 0; j < s.length() / i; j++) {
sb.append(str);
}
if (sb.toString().equals(s)) {
return str;
}
}
return s;
}
}