Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2411. Smallest Subarrays With Maximum Bitwise OR #174

Open
Woodyiiiiiii opened this issue Jan 12, 2023 · 0 comments
Open

Leetcode 2411. Smallest Subarrays With Maximum Bitwise OR #174

Woodyiiiiiii opened this issue Jan 12, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

这道题我一直在尝试找到某种规律,但最后还没找到。

关键是从位数思考|与最大值的关系

对于某个数nums[i],要往后循环找到最大的数,就是尽可能在位数上获得更多的、最近的1。所以提前预处理,向前遍历存储在每个节点上最近1位数的位置。

class Solution {
    public int[] smallestSubarrays(int[] nums) {
        int n = nums.length;
        int[] ans = new int[n];
        // the last appearance of index bits
        int[] last = new int[32];
        for (int i = n - 1; i >= 0; --i) {
            ans[i] = 1;
            for (int j = 0; j < 32; ++j) {
                if ((nums[i] & (1 << j)) > 0) {
                    last[j] = i;
                }
                ans[i] = Math.max(ans[i], last[j] - i + 1);
            }
        }
        return ans;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant