标签:ini nta ace ann span contain fun etc tin
package LeetCode_605 /** * 605. Can Place Flowers * https://leetcode.com/problems/can-place-flowers/ * You have a long flowerbed in which some of the plots are planted, and some are not. * However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0‘s and 1‘s, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule. Example 1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: true Example 2: Input: flowerbed = [1,0,0,0,1], n = 2 Output: false Constraints: 1. 1 <= flowerbed.length <= 2 * 10^4 2. flowerbed[i] is 0 or 1. 3. There are no two adjacent flowers in flowerbed. 4. 0 <= n <= flowerbed.length * */ class Solution { /* * solution: check current position prev and next if empty or not from left to right, * Time:O(n), Space:O(1) * */ fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean { if (flowerbed == null || flowerbed.isEmpty()) { return false } var count = 0 var previous = 0 var next = 0 var i = 0 while (i < flowerbed.size && count < n) { //if current is empty if (flowerbed[i] == 0) { /* * in start and last position, set it‘s prev and next to 0, for example [0,0,1,0,1], * we can put flower in position 0 * */ previous = if (i == 0) 0 else flowerbed[i - 1] next = if (i == flowerbed.size - 1) 0 else flowerbed[i + 1] if (previous == 0 && next == 0) { //put flower in flowerbed[i] = 1 count++ } } i++ } return count == n } }
标签:ini nta ace ann span contain fun etc tin
原文地址:https://www.cnblogs.com/johnnyzhao/p/14235091.html