双指针 发表于 2020-02-27 | 分类于 算法 , 双指针 | 本文总阅读量 题目一删除排序数组中的重复项 123456789101112131415161718class Solution { /** * @param Integer[] $nums * @return Integer */ function removeDuplicates(&$nums) { $length = count($nums); $i = 0; for($j = 1;$j<$length;$j++) { if ($nums[$j] != $nums[$i]) { $i++; $nums[$i] = $nums[$j]; } } return $i + 1; }} 题目二删除链表的倒数第N个节点 1234567891011121314151617181920212223242526272829303132/** * Definition for a singly-linked list. * class ListNode { * public $val = 0; * public $next = null; * function __construct($val) { $this->val = $val; } * } */class Solution { /** * @param ListNode $head * @param Integer $n * @return ListNode */ function removeNthFromEnd($head, $n) { $slow = $fast = $head; while ($n>0) { $n--; $fast = $fast->next; } while($fast != null && $fast->next != null) { $fast = $fast->next; $slow = $slow->next; } if ($slow == $head && $fast == null) { return $head->next; } $slow->next = $slow->next->next; return $head; }} 题目三三数之和 123456789101112131415161718192021222324252627282930313233343536373839404142class Solution { /** * @param Integer[] $nums * @return Integer[][] */ function threeSum($nums) { if (count($nums) < 3) { return []; } $res = []; sort($nums); $length = count($nums); for ($i = 0; $i < $length-2;$i++) { $start = $i+1; $end = $length-1; if ($i>0&&$nums[$i]==$nums[$i-1]) { continue; } while ($start < $end) { if (($nums[$i] + $nums[$start] + $nums[$end]) == 0) { $res[] = [$nums[$i], $nums[$start], $nums[$end]]; while($start<$end && $nums[$start] == $nums[$start+1]) { $start++; } while($start<$end && $nums[$end] == $nums[$end-1]) { $end--; } $start++; $end--; } elseif (($nums[$i] + $nums[$start] + $nums[$end]) > 0) { $end--; } else { $start++; } } } return $res; }}