Skip to content

Commit aee7534

Browse files
committed
feat: new stydy 📄
1 parent b44db07 commit aee7534

File tree

2 files changed

+110
-0
lines changed

2 files changed

+110
-0
lines changed

package/Other/MonkeyKing.php

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<?php
2+
3+
/**
4+
* MonkeyKing
5+
*
6+
* @author Pu ShaoWei <[email protected]>
7+
* @date 2017/8/23
8+
* @license Mozilla
9+
* -------------------------------------------------------------
10+
* 思路分析:单项循环数据链表 
11+
* -------------------------------------------------------------
12+
*有M个monkey ,转成一圈,第一个开始数数,数到第N个出圈,下一个再从1开始数,再数到第N个出圈,直到圈里只剩最后一个就是大王
13+
*/
14+
class MonkeyKing
15+
{
16+
protected $next;
17+
protected $name;
18+
19+
/**
20+
* MonkeyKing constructor.
21+
*
22+
* @param $name
23+
*/
24+
public function __construct($name)
25+
{
26+
$this->name = $name;
27+
}
28+
29+
/**
30+
* whoIsKing
31+
*
32+
* @static
33+
* @param $count
34+
* @param $num
35+
* @return mixed
36+
*/
37+
public static function whoIsKing($count, $num)
38+
{
39+
// 构造单向循环链表
40+
$current = $first = new MonkeyKing(1);
41+
for ($i = 2; $i <= $count; $i++){
42+
$current->next = new MonkeyKing($i);
43+
$current = $current->next;
44+
}
45+
// 最后一个指向第一个
46+
$current->next = $first;
47+
// 指向第一个
48+
$current = $first;
49+
// 定义一个数字
50+
$cn = 1;
51+
while ($current !== $current->next){
52+
$cn++;
53+
if ($cn == $num) {
54+
$current->next = $current->next->next;
55+
$cn = 1;
56+
}
57+
$current = $current->next;
58+
}
59+
// 返回猴子姓名
60+
return $current->name;
61+
}
62+
}
63+
64+
// 共10个猴子每3个出圈
65+
var_dump(MonkeyKing::whoIsKing(10, 3));
66+

package/Query/QulickQuery.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
/**
4+
* QulickQuery
5+
*
6+
* @author Pu ShaoWei <[email protected]>
7+
* @date 2017/8/23
8+
* @license Mozilla
9+
* -------------------------------------------------------------
10+
* 思路分析:数组中间的值floor((low+top)/2) 
11+
* -------------------------------------------------------------
12+
* 重复第二步操作直至找出目标数字
13+
*/
14+
15+
/**
16+
* @param $array
17+
* @param $k
18+
* @param int $low
19+
* @param int $high
20+
* @return int
21+
*/
22+
function QulickQuery($array, $k, $low = 0, $high = 0)
23+
{
24+
//判断是否为第一次调用
25+
if (count($array) != 0 and $high == 0) {
26+
$high = count($array);
27+
}
28+
//如果还存在剩余的数组元素
29+
if ($low <= $high) {
30+
//取$low和$high的中间值
31+
$mid = intval(($low + $high) / 2);
32+
//如果找到则返回
33+
if ($array[ $mid ] == $k) {
34+
return $mid;
35+
}else if ($k < $array[ $mid ]) {//如果没有找到,则继续查找
36+
return QulickQuery($array, $k, $low, $mid - 1);
37+
} else {
38+
return QulickQuery($array, $k, $mid + 1, $high);
39+
}
40+
}
41+
return -1;
42+
}
43+
44+
echo QulickQuery([4, 5, 7, 8, 9, 10, 8], 8);

0 commit comments

Comments
 (0)