美文网首页
605. Can Place Flowers

605. Can Place Flowers

作者: Super_Alan | 来源:发表于2018-04-22 03:21 被阅读0次

    https://leetcode.com/problems/can-place-flowers/description/

    题解:

    class Solution {
        public boolean canPlaceFlowers(int[] flowerbed, int n) {
            int sum = 0;
            LinkedList<Integer> list = new LinkedList<>();
            for (int i = 0; i < flowerbed.length; i++) {
                if (flowerbed[i] == 1) {
                    int betweenCnt = 0;
                    if (list.size() > 0) {
                        betweenCnt = (i - list.getLast() - 2) / 2;
                    } else {
                        betweenCnt = (i > 1) ? (i - 2) / 2 + 1: 0;
                    }
                    sum += betweenCnt;
                    list.add(i);
                }            
            }
            
            if (list.isEmpty()) {
                sum += (flowerbed.length + 1) / 2;
            } else {
                int betweenCnt = 0;
                if (list.getLast() < flowerbed.length - 2) {
                    betweenCnt = (flowerbed.length - 1 - list.getLast() - 2) / 2 + 1;
                }
                sum += betweenCnt;
            }
            
            return sum >= n;
        }
    }
    

    发现直接 Greedy 种花更简单。

        public boolean canPlaceFlowers(int[] flowerbed, int n) {
            for (int i = 0; i < flowerbed.length; i++) {
                if (flowerbed[i] == 0 
                        && (i == 0 || flowerbed[i - 1] == 0) 
                        && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
                    flowerbed[i] = 1;
                    n--;
                }
            }
            
            return n <= 0;
        }
    

    相关文章

      网友评论

          本文标题:605. Can Place Flowers

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