harrytothemoon / leetcodeAplus

Leetcode meeting note
2 stars 0 forks source link

[941] Valid Mountain Array #64

Open tsungtingdu opened 3 years ago

tsungtingdu commented 3 years ago
var validMountainArray = function(A) {
    let turns = 0

    for (let i = 1; i < A.length - 1; i++) {
      let diff = isPositive(A[i] - A[i-1]) - isPositive(A[i+1] - A[i])
      if (isPositive(A[i] - A[i-1]) === 0 || isPositive(A[i+1] - A[i]) === 0) {
        return false
      } else if (diff > 0) {
        turns += 1
      } else if (diff == 0) {
      } else {
        return false
      }
    }

    if (turns === 1) return true
    return false
};

function isPositive(x) {
  if (x > 0) {
    return 1
  } else if (x === 0) {
    return 0
  } else {
    return -1
  }
}
harrytothemoon commented 3 years ago

暴力解

var validMountainArray = function(arr) {
    if (arr.length < 3) return false
    let viewer = 0
    let maxIdx = arr.indexOf(Math.max(...arr))
    if (maxIdx === arr.length - 1 || maxIdx === 0) return false
    while (viewer !== arr.length - 1) {
        if (viewer < maxIdx && arr[viewer] >= arr[viewer + 1]) return false
        if (viewer >= maxIdx && arr[viewer] <= arr[viewer + 1]) return false
        viewer++
    }
    return true
};