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 2419. Longest Subarray With Maximum Bitwise AND #140

Open
Woodyiiiiiii opened this issue Sep 25, 2022 · 0 comments
Open

Leetcode 2419. Longest Subarray With Maximum Bitwise AND #140

Woodyiiiiiii opened this issue Sep 25, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

这道题中,一开始看到subArray想到利用滑动窗口的方法,但问题是:

  1. 窗口左边界缩小时如何排除元素?&运算不可逆
  2. &运算最大值,多个数的&运算不会超过他们的最大值
  3. 题目暗示了先找到最大值

所以要冷静,逻辑思考

class Solution {
    public int longestSubarray(int[] nums) {
        int max = 0;
        List<Integer> list = new ArrayList<>();

        for (int i = 0; i < nums.length; ++i) {
            if (nums[i] > max) {
                list.clear();
                list.add(i);
                max = nums[i];
            } else if (nums[i] == max) {
                list.add(i);
            }
        }

        int result = 1;
        int len = 0;
        int prev = -1;
        for (Integer integer : list) {
            if (prev == -1 || integer == prev + 1) {
                ++len;
                result = Math.max(result, len);
            } else {
                len = 1;
            }
            prev = integer;
        }

        return result;
    }
}

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