leetcode解题之485. Max Consecutive Ones Java版 (二进制连续最长1的个数)
2017-03-25 08:54
344 查看
485. Max Consecutive Ones
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
0and
1.
The length of input array is a positive integer and will not exceed 10,000
public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int result = 0;
int temp = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0)
temp = 0;
else {
temp += 1;
result = Math.max(temp, result);
}
}
return result;
}
// 动态规划
public int findMaxConsecutiveOnes(int[] nums) {
// 才用逆向思维,数组长度要加1
int dp[] = new int[nums.length + 1];
int max = 0;
for (int i = nums.length - 1; i >= 0; i--)
if (nums[i] == 1) {
dp[i] = dp[i + 1] + 1;
max = Math.max(dp[i], max);
}
return max;
}
// 动态规划
public int findMaxConsecutiveOnes(int[] nums) {
int dp[] = new int[nums.length];
int max = 0;
for (int i = 0; i < nums.length; i++)
if (nums[i] == 1) {
if (i == 0)
dp[i] = 1;
else
dp[i] = dp[i - 1] + 1;
max = Math.max(dp[i], max);
}
return max;
}
}
相关文章推荐
- Leetcode 128. Longest Consecutive Sequence 最长连续序列 解题报告
- 查找一个int数的二进制中连续最长的1开始出现的索引
- [LeetCode] 674. Longest Continuous Increasing Subsequence 最长连续递增序列
- LeetCode 485 Max Consecutive Ones 最大连续1的个数
- [LeetCode] Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之二
- LeetCode | Longest Substring Without Repeating Characters(最长连续不重复子串)
- LeetCode(Longest Consecutive Sequence ) 最长连续序列
- leetcode解题之3. Longest Substring Without Repeating Characters Java版(最长子串长度)
- [LeetCode] Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之二
- Leetcode 424. Longest Repeating Character Replacement 替换得到最长序列 解题报告
- Leetcode 485. Max Consecutive Ones 最大连续1 解题报告
- [LeetCode] 549. Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之 II
- leetcode之最长连续子串之set和unordered_set.
- LeetCode 3. Longest Substring Without Repeating Characters(最长不重复连续子串)
- Longest Consecutive Sequence (最长连续序列) 【面试算法leetcode】
- 【leetcode】最长连续序列(unordered_map的使用)
- [LeetCode] Longest Consecutive Sequence 求最长连续序列
- Leetcode 401. Binary Watch 二进制的表 解题报告
- LeetCode-674:Longest Continuous Increasing Subsequence (最长连续增序列)
- [LeetCode 128] - 最长连续序列(Longest Consecutive Sequence)