Untitled
unknown
plain_text
a year ago
1.1 kB
9
Indexable
/* It calculates the parity change between adjacent elements in nums, stores the prefix sum of these changes, and then determines if the parity change within a given range specified by each query matches the length of the range. The result is stored in a boolean array ans, which is returned at the end. */ class Solution { public boolean[] isArraySpecial(int[] nums, int[][] queries) { int n = nums.length; int[] parityChange = new int[n - 1]; for (int i = 0; i < n - 1; i++) { parityChange[i] = (nums[i] % 2 != nums[i + 1] % 2) ? 1 : 0; } int[] prefixSum = new int[n]; for (int i = 1; i < n; i++) { prefixSum[i] = prefixSum[i - 1] + (i-1<n-1?parityChange[i-1]:0); } boolean[] ans = new boolean[queries.length]; for (int i = 0; i < queries.length; i++) { int start=queries[i][0]; int end=queries[i][1]; if (start==end) { ans[i]=true; } else { ans[i]=(prefixSum[end] -prefixSum[start]==end-start); } } return ans; } }
Editor is loading...
Leave a Comment