美文网首页
求数组中连续出现 0 最多的次数

求数组中连续出现 0 最多的次数

作者: 不知道的是 | 来源:发表于2018-11-26 16:18 被阅读0次
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <script>
    const arr1 = [2, 5, 3, 2, 0, 1, 2, 0, 0, 5, 8, 7, 1, 12, 0, 16, 0, 0, 0, 9, 7, 0, 0, 0, 0]
    const arr2 = [2, 5, 3, 2, 0, 1, 2, 0, 0, 5]
    const arr3 = [32, 5, 3, 2, 10, 1, 2, 0, 0, 0, 0, 5, 10, 2, 5, 0, 0, 0, 0, 0, 5, 0]
    const arr4 = [1, 2, 3, 4, 5]
    const arr5 = [1, 2, 3, 4, 0]

    function fn(arr) {
      const length = arr.length

      let list = []

      for (let i = 0; i < length; i++) {
        list.push(0)
      }

      let index = 0

      for (let i = 1; i < length; i++) {
        const x = arr[i - 1]
        const y = arr[i]
        const z = x - y
        // console.log(z)

        if (z === 0) {
          list[index] += 1
        }

        if (z !== 0) {
          if (list[index] === 0 && index === 0) {
            list[index++] = z > 0 ? -z : z
          } else if (list[index] > 0) {
            list[++index] = z > 0 ? -z : z
            index++
          } else {
            list[index++] = z > 0 ? -z : z
          }
        }
      }

      const filteredList = list.filter(function (value, index, array) {
        // console.log(value)
        return value >= 1
      })


      const finalList = filteredList.map(function (value, index, array) {
        return value + 1
      })

      // console.log(finalList)

      // const maxNumber = Math.max.apply(null, finalList)

      // return maxNumber

      let total = 0

      if (finalList.toString() !== '') {
        total = Math.max.apply(null, finalList)
      }

      return total
    }

    const value1 = fn(arr1)
    const value2 = fn(arr2)
    const value3 = fn(arr3)
    const value4 = fn(arr4)
    const value5 = fn(arr5)
    console.log(`连续出现 0 最多的次数为 ${value1}`)
    console.log(`连续出现 0 最多的次数为 ${value2}`)
    console.log(`连续出现 0 最多的次数为 ${value3}`)
    console.log(`连续出现 0 最多的次数为 ${value4}`)
    console.log(`连续出现 0 最多的次数为 ${value5}`)
  </script>
</body>

</html>
image.png

https://codepen.io/MonguDykrai/pen/PxayoO

相关文章

网友评论

      本文标题:求数组中连续出现 0 最多的次数

      本文链接:https://www.haomeiwen.com/subject/psbbqqtx.html