Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ce9c981

Browse files
author
scuyjzh
committed
add solutions to problem - "845. Longest Mountain in Array"
1 parent 07dbe0c commit ce9c981

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,7 @@
228228
| 42 | [接雨水](https://leetcode-cn.com/problems/trapping-rain-water/) | [Java](./src/com/scuyjzh/leetcode/hard/No_0042_Trapping_Rain_Water/Solution.java) | 困难 | 栈 数组 双指针 动态规划 单调栈 |
229229
| 658 | [找到 K 个最接近的元素](https://leetcode-cn.com/problems/find-k-closest-elements/) | [Java](./src/com/scuyjzh/leetcode/medium/No_0658_Find_K_Closest_Elements/Solution.java) | 中等 | 数组 双指针 二分查找 排序 堆(优先队列) |
230230
| 259 | [较小的三数之和](https://leetcode-cn.com/problems/3sum-smaller/) 🔒 | [Java](./src/com/scuyjzh/leetcode/medium/No_0259_3Sum_Smaller/Solution.java) | 中等 | 数组 双指针 二分查找 排序 |
231+
| 845 | [数组中的最长山脉](https://leetcode-cn.com/problems/longest-mountain-in-array/) | [Java](./src/com/scuyjzh/leetcode/medium/No_0845_Longest_Mountain_in_Array/Solution.java) | 中等 | 数组 双指针 动态规划 枚举 |
231232

232233
### Array
233234

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.scuyjzh.leetcode.medium.No_0845_Longest_Mountain_in_Array;
2+
3+
/**
4+
* 845. 数组中的最长山脉
5+
*
6+
* 把符合下列属性的数组 arr 称为 山脉数组 :
7+
* • arr.length >= 3
8+
* • 存在下标 i(0 < i < arr.length - 1),满足
9+
* しろまる arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
10+
* しろまる arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
11+
*
12+
* 给出一个整数数组 arr,返回最长山脉子数组的长度。如果不存在山脉子
13+
* 数组,返回 0 。
14+
*/
15+
class Solution {
16+
/**
17+
* 方法:双指针
18+
*/
19+
public int longestMountain(int[] arr) {
20+
int n = arr.length;
21+
int res = 0;
22+
int left = 0, right;
23+
while (left + 2 < n) {
24+
right = left + 1;
25+
// 山脉开始一定上升
26+
if (arr[left] < arr[left + 1]) {
27+
// 找到山顶
28+
while (right + 1 < n && arr[right] < arr[right + 1]) {
29+
++right;
30+
}
31+
// 山顶之后必须下降
32+
if (right + 1 < n && arr[right] > arr[right + 1]) {
33+
while (right + 1 < n && arr[right] > arr[right + 1]) {
34+
++right;
35+
}
36+
res = Math.max(res, right - left + 1);
37+
}
38+
}
39+
left = right;
40+
}
41+
return res;
42+
}
43+
44+
public static void main(String[] args) {
45+
System.out.println(new Solution().longestMountain(new int[]{2, 1, 4, 7, 3, 2, 5}));
46+
}
47+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /