Input: nums =[2,1,4]Output: trueExplanation:
There is only two pairs:`(2,1)` and `(1,4)`, and both of them contain numbers with different parity. So the answer is`true`.
An array is considered special if every pair of its adjacent elements contains two numbers with different parity (one even and one odd, or vice versa).
A number is odd if number % 2 == 1
A number is even if number % 2 == 0
To verify that an array is special, we need to check each pair of adjacent elements.
Here is the approach:
Iterate through the array checking each pair of adjacent elements.
Ensure they have different parity.
If any pair has the same parity, return false.
If all pairs have different parities, return true.
classSolution {
publicbooleanisArraySpecial(int[] nums) {
for (int i = 1; i < nums.length; i++) {
if ((nums[i]% 2) == (nums[i - 1]% 2)) {
returnfalse;
}
}
returntrue;
}
}
1
2
3
4
5
6
classSolution:
defisArraySpecial(self, nums: List[int]) -> bool:
for i in range(1, len(nums)):
if (nums[i] %2) == (nums[i -1] %2):
returnFalsereturnTrue
classSolution {
publicbooleanisArraySpecial(int[] nums) {
for (int i = 1; i < nums.length; i++) {
if (((nums[i]& 1) ^ (nums[i - 1]& 1)) == 0) {
returnfalse;
}
}
returntrue;
}
}
1
2
3
4
5
6
classSolution:
defisArraySpecial(self, nums: List[int]) -> bool:
for i in range(1, len(nums)):
if (nums[i] &1) == (nums[i -1] &1):
returnFalsereturnTrue