问题描述:(找出奇数数组中唯一的偶数,或是偶数数组中唯一的奇数)
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。