LeetCode 按位或最大的最小子数组长度 - 滑动窗口

LeetCode 按位或最大的最小子数组长度 - 滑动窗口

🟠 中等偏上 https://leetcode.cn/problems/smallest-subarrays-with-maximum-bitwise-or/description/

记录每位1的最近位置

class Solution {

public:

    vector<int> smallestSubarrays(vector<int>& nums) {

        int n = nums.size();

        int right = n-1;

        int and_res = 0;

        int count[32];

        vector<int> res(n,0);

        for(int i = n-1;i>=0;i--){

            for(int j = 0;j<32;j++){
				//及时更新1的位置,是最近的位置。
                if(nums[i]&(1<<j)) count[j] = i;

            }

  

            int farst_right = i;

            for(int k = 0;k<32;k++){
				// 找到最远的最近1
                farst_right = max(farst_right,count[k]);

            }

  
			
            res[i] = farst_right-i+1;

        }

        return res;

    }

};

按结果分类

https://www.bilibili.com/video/BV1MT411u7fW/?vd_source=a9a24992f7f570a16d5a331e8fed9f0d

将 i 右侧按或的结果分为n段,i-1时,只用或上结果就行,合并相同的段。

class Solution {

public:

    vector<int> smallestSubarrays(vector<int>& nums) {

        vector<pair<int,int>> or_res_index;

        int n = nums.size();

        vector<int> res(n,0);

        for( int i = n-1;i>=0;i--){

            or_res_index.emplace_back(0,i);

            for(int j = 0;j<or_res_index.size();j++){

                or_res_index[j].first |=nums[i];

            }

            int fast = 0,slow = 0;

            while(fast<or_res_index.size()){

                if(or_res_index[slow].first!=or_res_index[fast].first){

                    slow++;

                    or_res_index[slow] = or_res_index[fast];

                }

                or_res_index[slow].second = or_res_index[fast].second;

                fast++;

            }

            or_res_index.resize(slow+1);

            res[i] = or_res_index[0].second-i+1;

  

        }

        return res;

    }

};