Netflix OA 面试真题解析:Alternating Parity Pattern(交替奇偶模式)

18次阅读
没有评论

An array is considered to follow an alternating parity pattern if it does not contain two consecutive integers of the same parity. In other words, consecutive integers in the array should never be two even numbers or two odd numbers.

Given an array of non-negative integers numbers, determine whether there are elements which break the alternating parity pattern.

Return the index of the first element where the alternating parity pattern breaks, or -1 if there are no such elements.

Example

  • For numbers = [1, 2, 5, 3, 6], the output should be solution(numbers) = 3.
  • Since both numbers[2] = 5 and numbers[3] = 3 are odd, the first index where the alternating parity pattern breaks is numbers[3].
  • For numbers = [1, 4, 7, 2, 5, 6], the output should be solution(numbers) = -1.
  • All elements in even-numbered positions are odd, and all elements in odd-numbered positions are even, so there are no indices where the pattern breaks.

这道题要求检查数组是否满足“奇偶交替”模式:相邻两个数不能同为偶数或同为奇数。最直接的做法是从左到右遍历数组,比较每一对相邻元素的奇偶性;一旦发现 <code>numbers[i]</code> 和 <code>numbers[i-1]</code> 同奇偶,就返回当前位置 <code>i</code>,因为它是第一次打破模式的元素下标。如果整个数组都满足交替规律,则返回 <code>-1</code>。题目规模只有 1000,线性扫描即可轻松通过。

正文完
 0