[C++][Java] Clean Code


  • 6

    C++

    class Solution {
    public:
        bool canPlaceFlowers(vector<int>& bed, int n) {
            for (int i = 0; i < bed.size(); i++) {
                if (!bed[i] && (i == 0 || !bed[i - 1]) && (i == bed.size() - 1 || !bed[i + 1])) {
                    bed[i] = 1;
                    n--;
                }
            }
            return n <= 0;
        }
    };
    

    Java

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

  • 2
    D

    neat solution for this problem, but it may be not good to modify the original array


  • 0
    Z

    Neat and concise! thanks for sharing solution!


  • 0
    L

    @alexander how can we get (i == 0 || bed[i - 1] == 0) && (i == bed.length - 1 || bed[i + 1] == 0)?
    Is it simplified from the original logic or wrote straitforward?


  • 1

    @liuzhou1992 it is trying to say bed[i-1] == 0 && bed[i+1] == 0, but need to check boundary case


  • 0
    L

    @alexander I see..Thx for replying!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.