Цена за 48 часов в ленте | 450,00 |
Цена за 1 час закрепления | — |
Взаимопиар | Нет |
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.
class Solution {
function eraseOverlapIntervals($intervals) {
usort($intervals, function($a, $b) {
return $a[1] - $b[1];
});
$ans = 0;
$k = -INF;
foreach ($intervals as $interval) {
list($x, $y) = $interval;
if ($x >= $k) {
$k = $y;
} else {
$ans++;
}
}
return $ans;
}
}
Количество байтов | UTF-8 Октетная последовательность
| (бинарная)
--------------------+-----------------------------------------
1 | 0xxxxxxx
2 | 110xxxxx 10xxxxxx
3 | 1110xxxx 10xxxxxx 10xxxxxx
4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
Input: data = [197,130,1]
Output: true
Explanation: data represents the octet sequence: 11000101 10000010 00000001.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
class Solution {
function validUtf8($data) {
$nBytes = 0;
foreach ($data as $num) {
$binRep = substr(sprintf('%08b', $num), -8);
if ($nBytes == 0) {
foreach (str_split($binRep) as $bit) {
if ($bit == '0') break;
$nBytes++;
}
if ($nBytes == 0) continue;
if ($nBytes == 1 || $nBytes > 4) return false;
} else {
if (!(substr($binRep, 0, 2) == '10')) return false;
}
$nBytes--;
}
return $nBytes == 0;
}
}
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
class ListNode {
public $val;
public $next;
public function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
function hasCycle($head) {
$nodesSeen = [];
$current = $head;
while ($current !== null) {
$nodeId = spl_object_id($current);
if (isset($nodesSeen[$nodeId])) {
return true;
}
$nodesSeen[$nodeId] = true;
$current = $current->next;
}
return false;
}
Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
function findAnagrams($s, $p) {
$ns = strlen($s);
$np = strlen($p);
if ($ns < $np) {
return [];
}
$pCount = array_fill_keys(range('a', 'z'), 0);
$sCount = array_fill_keys(range('a', 'z'), 0);
for ($i = 0; $i < $np; $i++) {
$pCount[$p[$i]]++;
}
$output = [];
for ($i = 0; $i < $ns; $i++) {
$sCount[$s[$i]]++;
if ($i >= $np) {
$leftChar = $s[$i - $np];
if ($sCount[$leftChar] == 1) {
unset($sCount[$leftChar]);
} else {
$sCount[$leftChar]--;
}
}
if ($pCount == $sCount) {
$output[] = $i - $np + 1;
}
}
return $output;
}
Input: nums = [1,4,2,5,3]
Output: 11
Explanation: There are 11 valid subarrays: [1],[4],[2],[5],[3],[1,4],[2,5],[1,4,2],[2,5,3],[1,4,2,5],[1,4,2,5,3].
class Solution {
function validSubarrays($nums) {
$ans = 0;
$st = [];
for ($i = 0; $i < count($nums); $i++) {
while (!empty($st) && $nums[$i] < $nums[end($st)]) {
$ans += ($i - array_pop($st));
}
$st[] = $i;
}
while (!empty($st)) {
$ans += (count($nums) - array_pop($st));
}
return $ans;
}
}
Input: n = 2
Output: ["11","69","88","96"]
class Solution {
private $reversiblePairs = [
['0', '0'], ['1', '1'],
['6', '9'], ['8', '8'], ['9', '6']
];
private function generateStroboNumbers($n, $finalLength) {
if ($n == 0) {
return [""];
}
if ($n == 1) {
return ["0", "1", "8"];
}
$prevStroboNums = $this->generateStroboNumbers($n - 2, $finalLength);
$currStroboNums = [];
foreach ($prevStroboNums as $prevStroboNum) {
foreach ($this->reversiblePairs as $pair) {
if ($pair[0] != '0' || $n != $finalLength) {
$currStroboNums[] = $pair[0] . $prevStroboNum . $pair[1];
}
}
}
return $currStroboNums;
}
public function findStrobogrammatic($n) {
return $this->generateStroboNumbers($n, $n);
}
}
Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"
Output: [true,false,true,true,false]
class Solution {
function camelMatch($queries, $pattern) {
function matches($query, $pattern) {
$i = 0;
$j = 0;
while ($i < strlen($query)) {
if ($j < strlen($pattern) && $query[$i] == $pattern[$j]) {
$j++;
} else if (ctype_upper($query[$i])) {
return false;
}
$i++;
}
return $j == strlen($pattern);
}
$answer = [];
foreach ($queries as $query) {
$answer[] = matches($query, $pattern);
}
return $answer;
}
}
Input: nums = [1,3,4,2,2]
Output: 2
class Solution {
function findDuplicate($nums) {
$duplicate = -1;
for ($i = 0; $i < count($nums); $i++) {
$cur = abs($nums[$i]);
if ($nums[$cur] < 0) {
$duplicate = $cur;
break;
}
$nums[$cur] *= -1;
}
for ($i = 0; $i < count($nums); $i++) {
$nums[$i] = abs($nums[$i]);
}
return $duplicate;
}
}
Input: head = [1,2,2,1]
Output: true
class Solution {
function isPalindrome($head) {
$vals = [];
$currentNode = $head;
while ($currentNode !== null) {
$vals[] = $currentNode->val;
$currentNode = $currentNode->next;
}
$front = 0;
$back = count($vals) - 1;
while ($front < $back) {
if ($vals[$front] != $vals[$back]) {
return false;
}
$front++;
$back--;
}
return true;
}
}
Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
Output: "Sao Paulo"
Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo".
class Solution {
function destCity($paths) {
foreach ($paths as $path) {
$candidate = $path[1];
$good = true;
foreach ($paths as $p) {
if ($p[0] === $candidate) {
$good = false;
break;
}
}
if ($good) {
return $candidate;
}
}
return "";
}
}
Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
class Solution {
function findDiagonalOrder($mat) {
if (empty($mat) || empty($mat[0])) return [];
$N = count($mat);
$M = count($mat[0]);
$result = [];
for ($d = 0; $d < $N + $M - 1; $d++) {
$intermediate = [];
$r = $d < $M ? 0 : $d - $M + 1;
$c = $d < $M ? $d : $M - 1;
while ($r < $N && $c >= 0) {
$intermediate[] = $mat[$r][$c];
$r++;
$c--;
}
if ($d % 2 == 0) {
$intermediate = array_reverse($intermediate);
}
$result = array_merge($result, $intermediate);
}
return $result;
}
}
Input: nums = [1,3,5]
Output: 1
class Solution {
function findMin($nums) {
$low = 0;
$high = count($nums) - 1;
while ($low < $high) {
$pivot = $low + intdiv($high - $low, 2);
if ($nums[$pivot] < $nums[$high]) {
$high = $pivot;
} else if ($nums[$pivot] > $nums[$high]) {
$low = $pivot + 1;
} else {
$high -= 1;
}
}
return $nums[$low];
}
}
Input: root = [0,0,null,0,null,0,null,null,0]
Output: 2
Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
class Solution {
function minCameraCover($root) {
$ans = $this->solve($root);
return min($ans[1], $ans[2]);
}
private function solve($node) {
if ($node == null) {
return [0, 0, 99999];
}
$L = $this->solve($node->left);
$R = $this->solve($node->right);
$mL12 = min($L[1], $L[2]);
$mR12 = min($R[1], $R[2]);
$d0 = $L[1] + $R[1];
$d1 = min($L[2] + $mR12, $R[2] + $mL12);
$d2 = 1 + min($L[0], $mL12) + min($R[0], $mR12);
return [$d0, $d1, $d2];
}
}
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
class TreeNode {
public $val;
public $left;
public $right;
public function __construct($val, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
class Solution {
function zigzagLevelOrder($root) {
$result = [];
if ($root === null) {
return $result;
}
$nodeQueue = new SplQueue();
$nodeQueue->enqueue($root);
$nodeQueue->enqueue(null);
$isOrderLeft = true;
$levelList = [];
while (!$nodeQueue->isEmpty()) {
$currentNode = $nodeQueue->dequeue();
if ($currentNode !== null) {
if ($isOrderLeft) {
$levelList[] = $currentNode->val;
} else {
array_unshift($levelList, $currentNode->val);
}
if ($currentNode->left !== null) {
$nodeQueue->enqueue($currentNode->left);
}
if ($currentNode->right !== null) {
$nodeQueue->enqueue($currentNode->right);
}
} else {
$result[] = $levelList;
$levelList = [];
if (!$nodeQueue->isEmpty()) {
$nodeQueue->enqueue(null);
}
$isOrderLeft = !$isOrderLeft;
}
}
return $result;
}
}
Input: root = [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
class TreeNode {
public $val = 0;
public $left = null;
public $right = null;
function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
class Solution {
function maxAncestorDiff($root) {
return $this->dfs($root, $root->val, $root->val);
}
private function dfs($node, $minVal, $maxVal) {
if ($node === null) return $maxVal - $minVal;
$minVal = min($minVal, $node->val);
$maxVal = max($maxVal, $node->val);
$left = $this->dfs($node->left, $minVal, $maxVal);
$right = $this->dfs($node->right, $minVal, $maxVal);
return max($left, $right);
}
}
Input: n = 1, k = 2
Output: "10"
function crackSafe($n, $k) {
$seen = [];
$result = [];
function dfs($node, $k, &$seen, &$result) {
for ($x = 0; $x < $k; $x++) {
$neighbor = $node . $x;
if (!in_array($neighbor, $seen)) {
$seen[] = $neighbor;
dfs(substr($neighbor, 1), $k, $seen, $result);
$result[] = $x;
}
}
}
$startNode = str_repeat("0", $n - 1);
dfs($startNode, $k, $seen, $result);
return $startNode . implode('', $result);
}
Input: mat = [[0,0],[0,1]]
Output: 1
class Solution {
function leftMostColumnWithOne($binaryMatrix) {
list($rows, $cols) = $binaryMatrix->dimensions();
$currentRow = 0;
$currentCol = $cols - 1;
while ($currentRow < $rows && $currentCol >= 0) {
if ($binaryMatrix->get($currentRow, $currentCol) == 0) {
$currentRow++;
} else {
$currentCol--;
}
}
return ($currentCol == $cols - 1) ? -1 : $currentCol + 1;
}
}
Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
function threeSumMulti($arr, $target) {
sort($arr);
$MOD = 1_000_000_007;
$count = 0;
for ($i = 0; $i < count($arr); $i++) {
$j = $i + 1;
$k = count($arr) - 1;
while ($j < $k) {
$sum = $arr[$i] + $arr[$j] + $arr[$k];
if ($sum == $target) {
if ($arr[$j] == $arr[$k]) {
$count += ($k - $j + 1) * ($k - $j) / 2;
break;
} else {
$left = 1;
$right = 1;
while ($j + 1 < $k && $arr[$j] == $arr[$j + 1]) {
$left++;
$j++;
}
while ($k - 1 > $j && $arr[$k] == $arr[$k - 1]) {
$right++;
$k--;
}
$count += $left * $right;
$j++;
$k--;
}
} elseif ($sum < $target) {
$j++;
} else {
$k--;
}
}
}
return $count % $MOD;
}
Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
class TreeNode {
public $val;
public $left;
public $right;
function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
function increasingBST($root) {
$nodes = [];
function inorder($node, &$nodes) {
if ($node === null) return;
inorder($node->left, $nodes);
$nodes[] = $node;
inorder($node->right, $nodes);
}
inorder($root, $nodes);
for ($i = 0; $i < count($nodes) - 1; $i++) {
$nodes[$i]->left = null;
$nodes[$i]->right = $nodes[$i + 1];
}
$nodes[count($nodes) - 1]->left = null;
$nodes[count($nodes) - 1]->right = null;
return $nodes[0];
}