[leetcode][845] Longest Mountain in Array

[leetcode][845] Longest Mountain in Array

Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:

  • B.length >= 3
  • There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]

(Note that B could be any subarray of A, including the entire array A.)

Given an array A of integers, return the length of the longest mountain.

Return 0 if there is no mountain.

Example 1:

Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.

Example 2:

Input: [2,2,2]
Output: 0
Explanation: There is no mountain.

Note:

  • 0 <= A.length <= 10000
  • 0 <= A[i] <= 10000

Follow up:

  • Can you solve it using only one pass?
  • Can you solve it in O(1) space?

解析:

找出最大的山形数组,这个数组必须是原数组的(连续的)子集,这个山形数组长度大于等于三,返回最长数组的长度。

参考答案(自己写的):

class Solution {
    public int longestMountain(int[] A) {
        if (A.length < 3) return 0;
        int result = 0;
        int count = 0;
        int top = 0;
        for (int i = 1; i < A.length; i++) {
            if (top == 0) {
                if (A[i] > A[i - 1]) {
                    count++;
                } else if (A[i - 1] > A[i] && count > 0) {
                    top = A[i - 1];
                    count++;
                } else {
                    count=0;
                }
            } else {
                if (A[i] < A[i - 1]) {
                    count++;
                } else if (A[i - 1] < A[i - 2]) {
                    result = result > count + 1 ? result : count + 1;
                    count = 0;
                    top = 0;
                }
                if (A[i] > A[i-1]) {
                    count++;
                }
            }
        }
        if (top != 0 && count > 0) {
            result = result > count + 1 ? result : count + 1;
        }

        return result;
    }
}

遍历数组设置一个top来保存顶点,判断顶点(假设给定的数组都是大于0的正整数)是否为零来判断是“上山”还是“下山”。

参考答案(别人的):

public int longestMountain(int[] A) {
    int res = 0, up = 0, down = 0;
    for (int i = 1; i < A.length; ++i) {
        if (down > 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;
}

别人的明显更简洁,效率也更高,少了很多判断,用up和down来分别计算“上山”和“下山”。

猜你喜欢

转载自www.cnblogs.com/ekoeko/p/9584659.html