Can Place Flowers:陣列相鄰元素不為0的插入問題
阿新 • • 發佈:2019-01-25
Suppose 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 - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n
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
Note:
- The input array won't violate no-adjacent-flowers rule.
- The input array size is in the range of [1, 20000].
- n is a non-negative integer which won't exceed the input array size.
思路:這是一道規律題
兩個1之間0的個數和可插入的1個數相關,相關關係為sum = (count-1)/2,count為兩個1之間區域性0的個數,sum為這一區域性可插入1的個數。
注意兩個邊界,如001可插入1,01則不可插入,解決辦法是兩側補零。
class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { //為了防止001001,100100,10,01這幾種特殊情況,在數列兩端各加一個0 StringBuilder sb = new StringBuilder(); sb.append(0); for(int i = 0;i<flowerbed.length;i++){ sb.append(flowerbed[i]); } sb.append(0); String s = sb.toString(); int sum = 0;//記錄全域性可容納數 int count = 0;//記錄區域性0的個數,區域性可容納數 = (區域性0的個數 - 1 )/2, //101 :0 //1001 :0 //10001 :1 //100001 :1 //1000001 : 2 //10000001 : 2 //...規律如上,零的個數:可容納數 for(int i = 0 ;i < s.length(); i++){ if(s.charAt(i)=='1'){ sum += (count-1)/2; count = 0; }else{ count ++; } } sum += (count -1) /2;//最後一組區域性在上面for迴圈中未新增,新增上。如100100 return (n<=sum)?true:false; } }