-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path136.只出现一次的数字.php
100 lines (91 loc) · 2.41 KB
/
136.只出现一次的数字.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
/*
* @lc app=leetcode.cn id=136 lang=php
*
* [136] 只出现一次的数字
*
* https://leetcode-cn.com/problems/single-number/description/
*
* algorithms
* Easy (71.28%)
* Likes: 1870
* Dislikes: 0
* Total Accepted: 406.2K
* Total Submissions: 568.3K
* Testcase Example: '[2,2,1]'
*
* 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
*
* 说明:
*
* 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
*
* 示例 1:
*
* 输入: [2,2,1]
* 输出: 1
*
*
* 示例 2:
*
* 输入: [4,1,2,1,2]
* 输出: 4
*
*/
// @lc code=start
class Solution
{
/**
* @param int[] $nums
* @return int
*/
public function singleNumber($nums)
{
//
// $total = count($nums);
// for ($i = 0; $i < $total; $i++) {
// for ($j = $i + 1; $j < $total; $j++) {
// // if ($j === count($nums)) {
// // // var_dump($j, count($nums), $nums, 'abc', $i);
// // return $nums[$i];
// // }
// if ($nums[$i] === $nums[$j]) {
// unset($nums[$i]);
// unset($nums[$j]);
// // $i = 0;
// // $j = $i + 1;
// // $nums = array_values($nums);
// // var_dump($nums);
// break;
// }
// }
// // return $nums[$i];
// }
// [-336,513,-560,-481,-174,101,-997,40,-527,-784,-283,-336,513,-560,-481,-174,101,-997,40,-527,-784,-283,354]
while (count($nums) !== 1) {
$i = 0;
$j = $i + 1;
$count = count($nums);
while ($j < $count) {
if ($nums[$i] === $nums[$j]) {
unset($nums[$i]);
unset($nums[$j]);
$nums = array_values($nums);
$i = 0;
$j = $i + 1;
break;
} else {
$j++;
}
}
if ($j === $count) {
// var_dump('here', $j, $nums);
return $nums[$i];
}
$i++;
}
// var_dump($nums);
return array_values($nums)[0];
}
}
// @lc code=end