zoukankan      html  css  js  c++  java
  • codewars--js--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.

    Examples

    [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)


    我的答案:
     1 function findOutlier(integers){
     2   //your code here
     3   var odd=[];
     5   var even=[];
     7   for( var i=0;i<integers.length;i++){
     8     if(integers[i]%2==0){
     9       even.push(integers[i]);
    10     }else{odd.push(integers[i]);}
    11   }
    12   if(even.length==1){return even.pop();}
    13   else{return odd.pop();}
    14  
    15 }

    优秀答案:
    (1)
    1 function findOutlier(int){
    2   var even = int.filter(a=>a%2==0);
    3   var odd = int.filter(a=>a%2!==0);
    4   return even.length==1? even[0] : odd[0];
    5 }

    关键问题:自己在解决问题的时候不会优先想到数组的方法,filter,forEach,map,reduce。

  • 相关阅读:
    Android性能优化--ANR
    Android性能优化--冷启动优化(Application)
    Android性能优化--UI卡顿
    Android性能优化--内存泄漏
    java反射
    数据结构之约瑟夫问题(循环链表)(C++版)
    数据结构之杨辉三角(队列实现)(C++版)
    vue组件间通信六种方式
    类型转换
    千分位
  • 原文地址:https://www.cnblogs.com/hiluna/p/8743094.html
Copyright © 2011-2022 走看看