Skip to content

Commit 160e49f

Browse files
author
git
committed
三数之和
1 parent 0fd6bbe commit 160e49f

2 files changed

Lines changed: 44 additions & 1 deletion

File tree

Week01/1.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
class Solution {
3+
4+
/**
5+
* @param Integer[] $nums
6+
* @return Integer[][]
7+
*/
8+
function threeSum($nums) {
9+
//数组个数小于3时
10+
if(count($nums) < 3) {
11+
return [];
12+
}
13+
//对数组进行升序排序
14+
sort($nums);
15+
$n = count($nums);
16+
$arr = [];
17+
18+
for($i=0;$i<$n; $i++) {
19+
if($nums[$i] > 0) return $arr;
20+
21+
if($i>0 && $nums[$i] == $nums[$i-1]) continue;
22+
$l = $i + 1;
23+
$r = $n - 1;
24+
while($l < $r) {
25+
$sum = $nums[$i] + $nums[$l] + $nums[$r];
26+
if($sum == 0) {
27+
array_push($arr,array($nums[$i],$nums[$l],$nums[$r]));
28+
29+
while(($nums[$l] == $nums[$l+1]) && ($l+1)<$n) ++$l;//这里注意index下标不能超过数组的范围
30+
while(($nums[$r] == $nums[$r-1]) && ($r-1)>0) --$r;
31+
++$l;
32+
--$r;
33+
}else if($sum < 0) {
34+
++$l;
35+
}else {
36+
--$r;
37+
}
38+
}
39+
}
40+
return $arr;
41+
}
42+
}

Week01/NOTE.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
学习笔记
1+
三数之和:排序+双指针的解法
2+
在左右指针移动,比较元素大小时,注意下标不能超出数组的范围,否则会报错:超出输出限制

0 commit comments

Comments
 (0)