Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

941. 有效的山脉数组 #69

Open
yankewei opened this issue Nov 3, 2020 · 1 comment
Open

941. 有效的山脉数组 #69

yankewei opened this issue Nov 3, 2020 · 1 comment
Labels
数组 题目类型为数组 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

yankewei commented Nov 3, 2020

给定一个整数数组 A,如果它是有效的山脉数组就返回 true,否则返回 false。

让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组:

  • A.length >= 3
  • 在 0 < i < A.length - 1 条件下,存在 i 使得:
    • A[0] < A[1] < ... A[i-1] < A[i]
    • A[i] > A[i+1] > ... > A[A.length - 1]
       
      pic

示例 1:

输入:[2,1]
输出:false

示例 2:

输入:[3,5,5]
输出:false

示例 3:

输入:[0,3,2,1]
输出:true

提示:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-mountain-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 数组 题目类型为数组 简单 题目难度为简单 labels Nov 3, 2020
@yankewei
Copy link
Owner Author

yankewei commented Nov 3, 2020

很简单,找到最大值,然后从头到最大值的过程应该是递增的,从最大值到尾的过程应该是递减的。

func validMountainArray(A []int) bool {
    index, maxValue := 0, 0
    for i, v := range A {
        if v > maxValue {
            maxValue = v
            index = i 
        }
    }
    if index == 0 || index == len(A)-1 {
        return false
    }

    for i := 0; i+1 <= index; i++ {
        if A[i] >= A[i+1] {
            return false
        }
    }

    for i := index; i+1 < len(A); i++ {
        if A[i] <= A[i+1] {
            return false
        }
    }
    return true
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
数组 题目类型为数组 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant