# 2401. Longest Nice Subarray ###### tags: `Leetcode` `Medium` `Sliding Window` Link: https://leetcode.com/problems/longest-nice-subarray/ ## 思路 记录每一个bit在window里面出现的最晚的位置 当一个新的数字来了我们看它有哪些bit 看这些bit是在哪个idx出现的 取最大的那个 直接把left移到它的下一位 就可以保证sliding window里面是nice subarray ## Code ```java= class Solution { public int longestNiceSubarray(int[] nums) { Map<Integer, Integer> curr = new HashMap<>(); int l=0, r=0; int n = nums.length; int ans = 1; while(r<n){ int delete = -1; for(int i=0; i<=31; i++){ if(((nums[r]>>i)&1)==1){ if(curr.containsKey(i)){ delete = Math.max(delete, curr.get(i)); } curr.put(i,r); } } if(delete!=-1) l = Math.max(l, delete+1); ans = Math.max(ans, r-l+1); r++; } return ans; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up