leetcode 485,487,1004. Max Consecutive Ones I ,II, III(最大连续1的个数问题合集)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 485,487,1004. Max Consecutive Ones I ,II, III(最大连续1的个数问题合集)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
485. Max Consecutive Ones
https://leetcode.com/problems/max-consecutive-ones/
easy 題,思路不說了,直接上代碼。
487. Max Consecutive Ones II
力扣這題需要 plus 會員,所以,為了保證“Max Consecutive Ones”的完整性,臨時用一下 lintcode。
https://www.lintcode.com/problem/883/
本題思路由題目 III 加了一個條件 k=1 改編而來。
另外,lintcode 的測試用例不夠全面,之前寫了一個明顯的 bug 但還是通過了,后來才發現,已更正。
public class Solution {public int findMaxConsecutiveOnes(int[] nums) {int k = 1;int cnt = 0;List<Integer> list = new ArrayList<>();for (int n : nums) {if (n == 0) {if (cnt != 0) list.add(cnt);list.add(0);cnt = 0;} else cnt++;}if (nums[nums.length - 1] == 1) list.add(cnt);int maxSum = 0;for (int i = 0; i < list.size(); i++) {int curSum = 0;int zeroCnt = 0;for (int j = i; j < list.size(); j++) {if (list.get(j) == 0) {if (++zeroCnt > k) break;curSum++;} else {curSum += list.get(j);}}maxSum = Math.max(maxSum, curSum);}if (maxSum == 0) {int zeroCnt = 0;for (Integer n : list) {if (n == 0) {if (++zeroCnt > k) break;maxSum++;} else {maxSum += n;}}}return maxSum;} }1004. Max Consecutive Ones III
https://leetcode.com/problems/max-consecutive-ones-iii/
普通思路
public class Solution {public int longestOnes(int[] nums, int k) {// 建立輔助數組int cnt = 0;List<Integer> list = new ArrayList<>();for (int n : nums) {if (n == 0) {if (cnt != 0) list.add(cnt);list.add(0);cnt = 0;} else cnt++;}if (nums[nums.length - 1] == 1) list.add(cnt); // 處理邊界// 利用輔助數組計算maxSumint maxSum = 0;for (int i = 0; i < list.size(); i++) {int curSum = 0;int zeroCnt = 0;for (int j = i; j < list.size(); j++) {if (list.get(j) == 0) {if (++zeroCnt > k) break;curSum++;} else {curSum += list.get(j);}}maxSum = Math.max(maxSum, curSum);}// 獨立處理因數組長度不足而無法進入for循環的情況if (maxSum == 0) {int zeroCnt = 0;for (Integer n : list) {if (n == 0) {if (++zeroCnt > k) break;maxSum++;} else {maxSum += n;}}}return maxSum;} }進階思路:滑動窗口
思路參考:https://leetcode-cn.com/problems/max-consecutive-ones-iii/solution/hua-dong-chuang-kou-de-liang-chong-jie-j-8ses/
雙指針法,時間復雜度O(n)。
public int longestOnes(int[] A, int K) {int left = 0;//窗口左邊的位置int right = 0;//窗口右邊的位置int zeroCount = 0;//窗口中0的個數for (; right < A.length; right++) {if (A[right] == 0) {zeroCount++;}//如果窗口中0的個數超過了K,要縮小窗口的大小if (zeroCount > K && A[left++] == 0)zeroCount--;}return right - left; }總結
以上是生活随笔為你收集整理的leetcode 485,487,1004. Max Consecutive Ones I ,II, III(最大连续1的个数问题合集)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 1047. Remov
- 下一篇: Squash my last X com