-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy path605.java
49 lines (46 loc) · 1.63 KB
/
605.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
__________________________________________________________________________________________________
sample 1 ms submission
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
for(int i=0; i<flowerbed.length; i++){
if(n==0)
return true;
if(flowerbed[i]==0 && (i==0 || flowerbed[i-1]==0)
&& (i==flowerbed.length-1 || flowerbed[i+1]==0)){
n--;
flowerbed[i] = 1;
}
}
return n==0;
}
}
__________________________________________________________________________________________________
sample 37184 kb submission
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
markUnplant(flowerbed);
Arrays.stream(flowerbed).forEach(System.out::print);
for (int i = 0; i < flowerbed.length; i++) {
if (flowerbed[i] == 0) {
flowerbed[i++] = 1;
n--;
}
}
return n <= 0;
}
private void markUnplant(int[] flowerbed) {
for (int i = 0; i < flowerbed.length; i++) {
if (flowerbed[i] == 1) {
markUnplant(i++, flowerbed);
}
}
}
private void markUnplant(int pos, int[] flowerbed) {
if (isValid(pos - 1, flowerbed)) flowerbed[pos - 1] = 1;
if (isValid(pos + 1, flowerbed)) flowerbed[pos + 1] = 1;
}
private boolean isValid(int pos, int[] flowerbed) {
return pos >= 0 && pos < flowerbed.length;
}
}
__________________________________________________________________________________________________