每日一道CodeWars——Find The Parity Outlier【6kyu】

289 阅读2分钟

题目:Find The Parity Outlier

题目描述:

You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N.

样例

[2, 4, 0, 100, 4, 11, 2602, 36]  
Should return: 11 (the only odd number)

[160, 3, 1719, 19, 11, 13, -21]  
Should return: 160 (the only even number)

个人部分

解题思路:

该题的解题思路并不复杂,主要完成两个工作,一是判断outlier是奇数还是偶数,二是遍历数组找到这个值。

根据题目描述,这个outlier只有一个,也就是说,如果outlier如果是奇数,那么该数组中,除了这个outlier是奇数,其余的都为偶数。因此,要判断outlier是奇数还是偶数,根据数组的前三个元素就可以判断。判断完后,只要使用JS数组的filter方法,将正确结果过滤出来即可。

具体实现:

  • 首先设置一个flag用于保存判断filter的结果。
  • 根据上述说明,根据前三个元素的奇偶性判断filter的属性,这里使用flag = 1表示filter为奇数,flag = 0表示filter为偶数,这里这样设置是为了让后续使用filter函数时,无需再判断filter是奇数还是偶数(因为偶数对2求余为0,奇数对2求余为1)。

需要注意的地方

  • 这里如果前三个元素均为偶数或奇数,将会导致flag为-1或2。因此我们还要再判断flag是否超出范围,若超出则需要重置为对应的值。
  • 在第一次提交的时候,忽略了负数这种情况。所以在判断的时候需要对其求绝对值在对2求余。

代码:

    let flag = -1;
    for(let i=0;i<3;i++){
      if(Math.abs(integers[i])%2==0) flag++
    }
    if(flag==2) flag = 1
    if(flag==-1) flag = 0
    return integers.filter(x=>Math.abs(x)%2==flag)[0]

其他部分

其他大佬解法

1. 使用两个filter

Array的filter函数接收一个回调函数,该函数测试数组的每个元素,测试结果返回一个布尔值。filter函数返回测试结果为true的数组元素。因此分别使用使用两次filter,将数组中的奇数和偶数分别筛选出来,然后选取数组长度为1的数组即为要的结果。

因此代码如下:

function findOutlier(int){
  var even = int.filter(a=>a%2==0);
  var odd = int.filter(a=>a%2!==0);
  return even.length==1? even[0] : odd[0];
}