嗨,大家好!刷題來到第三天了,一樣直接來看今天的題目吧!
/*
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
Note:
The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000
*/
var findMaxConsecutiveOnes = function(nums) {
}
這題一開始輸入會給一個二進位的陣列,我們必須找出在這個陣列中,最多的連續出現1,是幾個1。
思考:
var findMaxConsecutiveOnes = function(nums) {
let result = []
let count = 0
}
var findMaxConsecutiveOnes = function(nums) {
let result = []
let count = 0
for(let i = 0; i < nums.length; i++){
if(nums[i] === 1){
count += 1
}
if(nums[i] === 0){
result.push(count)
count = 0
}
}
}
var findMaxConsecutiveOnes = function(nums) {
nums.push(0)
let result = []
let count = 0
for(let i = 0; i < nums.length; i++){
if(nums[i] === 1){
count += 1
}
if(nums[i] === 0){
result.push(count)
count = 0
}
}
return Math.max(...result)
}
以上是今天內容!寫法上有非常大的進步空間。如果有哪位大大路過經過,還請多多賜教。
//解一
var findMaxConsecutiveOnes = function (nums) {
var maxCount = 0;//連續出現最大次數
var count = 0;//累加次數
nums.forEach(num => {
count = (num == 1) ? count += 1 : 0
maxCount = (count > maxCount) ? count : maxCount;
});
return maxCount;
}
//解二
var findMaxConsecutiveOnes = function (nums) {
return Math.max(...nums.join("").split(/0+/).map(text => text.length));
}
給你參考參考~~~