Skip to content

Commit e52af53

Browse files
author
uuk020
committed
在奇数数组中找出偶数或者在偶数数组中找出奇数 find
1 parent 42f203f commit e52af53

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

find/find.php

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
/**
3+
* 在奇数数组中找出偶数或者在偶数数组中找出奇数
4+
* You are given an array (which will have a length of at least 3, but could be very large) containing integers.
5+
* The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N.
6+
* Write a method that takes the array as an argument and returns this "outlier" N.
7+
* [2, 4, 0, 100, 4, 11, 2602, 36] Should return: 11 (the only odd number)
8+
* [160, 3, 1719, 19, 11, 13, -21] Should return: 160 (the only even number)
9+
*/
10+
function find($integers)
11+
{
12+
$odd = []; //偶数数组
13+
$even = []; // 奇数数组
14+
foreach ($integers as $value) {
15+
// 判断元素是否奇偶数
16+
if (($value & 1)) {
17+
// 是的入栈偶数数组
18+
array_push($odd, $value);
19+
} else {
20+
array_push($even, $value);
21+
}
22+
}
23+
// 判断偶数数组个数, 等于1, 说明该$integers数组有偶数
24+
if (count($odd) == 1) {
25+
return $odd[0];
26+
}
27+
if (count($even) == 1) {
28+
return $even[0];
29+
}
30+
}

0 commit comments

Comments
 (0)