K flip minimum number of consecutive bits

Topic connection:

https://leetcode-cn.com/problems/minimum-number-of-k-consecutive-bit-flips/

Subject to the effect:

A 0 in the array contains only 1 and in a K-bit inversion comprises selecting a length K (continuous) sub-array, while each subarray 0 changes to 1, and each 1 is changed to 0.

Returns the number of bits K flip required, so there is no array of elements of the value 0. If not possible, return -1.

Specific ideas:

Specific ideas are greedy, that is, from the left, directly across do not meet the flip operation, and finally check the entire array is not all 1's; however, this kind of TLE, the most troublesome time complexity may be close to O ( n * k).

 1 class Solution {
 2 public:
 3     int minKBitFlips(vector<int>& A, int K) {
 4     int len = A.size();
 5     int ans = -1;
 6     if(len == 0 )ans =- 1;
 7     else {
 8     int num = 0 , flag = 0;
 9     for(int i = 0 ; i< len ;i++ ){
10      if(A[i] == 0){flag=1;break;}    
11      }
12     if(!flag)ans = -1;
13     else {
14     for(int i = 0; i <= len - K ;i++ ){
15     if(A[i])continue;
16     num++;
17     for(int j = i ;j < i + K ; j++ ){
18     A[j]^=1;
19     }    
20     }
21     }
22     for(int i = 0 ; i< len ; i++ ){
23     if(!A[i]){num=-1;break;}
24     }
25     ans=num;
26     }
27     return ans;
28     }
29 };

Then specific optimization, we can actually put inside length K for loop to optimize away, where you can use ideological difference; every operation is carried out for the section K in a length, so when found in the current position 0, this time we flip at this point, and then look at the mark positions k points points back, this time is the need to prove

Turned over (this is equivalent to each mark inversion interval); and when determining whether particular flipped, we need to discuss the case; When the current position number is an odd number of inversion, the points 1, i.e. flipping or after an even number, this time is the need to flip, that is, two are 11. When the number of the current position is even reversed, this point is zero, this time is the need to flip; it is a comprehensive look at the current location when the number of flip == What is the current position of number this time is the need to flip.

. 1  class Solution {
 2      public :
 . 3      int minKBitFlips (Vector < int > & A, int K) {
 . 4      int In Flag [ 30000 + 100 ];
 . 5      Memset (In Flag, 0 , the sizeof (In Flag));
 . 6      int tmp = 0 ; / / tmp is inverted to record the number of the current position
 . 7      int len = a.size ();
 . 8      int NUM = 0 ;
 . 9      for ( int I = 0 ; I <len; I ++ ) {
10         tmp^=flag[i];
11         if(A[i] == tmp){
12             num++;
13             if(i + K > len)return -1;
14             tmp^=1;
15             flag[i+K]^=1;
16         }
17     }
18     return num;
19     }
20 };

 

Guess you like

Origin www.cnblogs.com/letlifestop/p/11183960.html
Recommended