Цена за 48 часов в ленте | 450,00 |
Цена за 1 час закрепления | N/A |
Взаимопиар | Нет |
Дополнительные условия рекламы | Отсутствуют |
Input
["WordDistance", "shortest", "shortest"]
[[["practice", "makes", "perfect", "coding", "makes"]], ["coding", "practice"], ["makes", "coding"]]
Output
[null, 3, 1]
Explanation
WordDistance wordDistance = new WordDistance(["practice", "makes", "perfect", "coding", "makes"]);
wordDistance.shortest("coding", "practice"); // return 3
wordDistance.shortest("makes", "coding"); // return 1
// PHP
class WordDistance {
private $locations;
function __construct($words) {
$this->locations = [];
foreach ($words as $i => $word) {
if (!isset($this->locations[$word])) {
$this->locations[$word] = [];
}
$this->locations[$word][] = $i;
}
}
function shortest($word1, $word2) {
$loc1 = $this->locations[$word1];
$loc2 = $this->locations[$word2];
$l1 = 0;
$l2 = 0;
$minDiff = PHP_INT_MAX;
while ($l1 < count($loc1) && $l2 < count($loc2)) {
$minDiff = min($minDiff, abs($loc1[$l1] - $loc2[$l2]));
if ($loc1[$l1] < $loc2[$l2]) {
$l1++;
} else {
$l2++;
}
}
return $minDiff;
wordsDict
и две разные строки, которые уже существуют в массиве: word1
и word2
. Верните кратчайшее расстояние между этими двумя словами в списке.Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
Output: 3
class Solution {
function shortestDistance($words, $word1, $word2) {
$minDistance = count($words);
for ($i = 0; $i < count($words); $i++) {
if ($words[$i] == $word1) {
for ($j = 0; $j < count($words); $j++) {
if ($words[$j] == $word2) {
$minDistance = min($minDistance, abs($i - $j));
}
}
}
}
return $minDistance;
}
}
Input: s = "anagram", t = "nagaram"
Output: true
function isAnagram($s, $t) {
if (strlen($s) != strlen($t)) {
return false;
}
$count = array_fill(0, 26, 0);
for ($i = 0; $i < strlen($s); $i++) {
$count[ord($s[$i]) - ord('a')]++;
$count[ord($t[$i]) - ord('a')]--;
}
foreach ($count as $c) {
if ($c != 0) {
return false;
}
}
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
Output: true
class Solution {
private function binarySearch($matrix, $target, $start, $vertical) {
$lo = $start;
$hi = $vertical ? count($matrix[0]) - 1 : count($matrix) - 1;
while ($hi >= $lo) {
$mid = intdiv($lo + $hi, 2);
$value = $vertical ? $matrix[$start][$mid] : $matrix[$mid][$start];
if ($value < $target) {
$lo = $mid + 1;
} else if ($value > $target) {
$hi = $mid - 1;
} else {
return true;
}
}
return false;
}
public function searchMatrix($matrix, $target) {
if ($matrix === null || count($matrix) === 0) return false;
$shorterDim = min(count($matrix), count($matrix[0]));
for ($i = 0; $i < $shorterDim; $i++) {
if ($this->binarySearch($matrix, $target, $i, true) || $this->binarySearch($matrix, $target, $i, false)) {
return true;
}
}
return false;
}
}
Input: n = 6
Output: true
Explanation: 6 = 2 × 3
class Solution {
function isUgly($n) {
if ($n <= 0) {
return false;
}
foreach ([2, 3, 5] as $factor) {
$n = $this->keepDividingWhenDivisible($n, $factor);
}
return $n == 1;
}
private function keepDividingWhenDivisible($dividend, $divisor) {
while ($dividend % $divisor == 0) {
$dividend /= $divisor;
}
return $dividend;
}
}
Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true
class Solution {
function validTree($n, $edges) {
if (count($edges) != $n - 1) {
return false;
}
$adjList = array_fill(0, $n, []);
foreach ($edges as $edge) {
$adjList[$edge[0]][] = $edge[1];
$adjList[$edge[1]][] = $edge[0];
}
$parent = [0 => -1];
$queue = [0];
while (!empty($queue)) {
$node = array_shift($queue);
foreach ($adjList[$node] as $neighbor) {
if ($neighbor == $parent[$node]) {
continue;
}
if (isset($parent[$neighbor])) {
return false;
}
$parent[$neighbor] = $node;
$queue[] = $neighbor;
}
}
return count($parent) == $n;
}
}
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.
class Solution {
public function singleNumber($nums) {
$xor = 0;
foreach ($nums as $num) {
$xor ^= $num;
}
$diff = $xor & -$xor;
$res = [0, 0];
foreach ($nums as $num) {
if (($num & $diff) == 0) {
$res[0] ^= $num;
} else {
$res[1] ^= $num;
}
}
return $res;
}
}
Input: nums = [-2,0,1,3], target = 2
Output: 2
Explanation: Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]
class Solution {
public function threeSumSmaller($nums, $target) {
sort($nums);
$sum = 0;
for ($i = 0; $i < count($nums) - 2; $i++) {
$sum += $this->twoSumSmaller($nums, $i + 1, $target - $nums[$i]);
}
return $sum;
}
private function twoSumSmaller($nums, $startIndex, $target) {
$sum = 0;
for ($i = $startIndex; $i < count($nums) - 1; $i++) {
$j = $this->binarySearch($nums, $i, $target - $nums[$i]);
$sum += $j - $i;
}
return $sum;
}
private function binarySearch($nums, $startIndex, $target) {
$left = $startIndex;
$right = count($nums) - 1;
while ($left < $right) {
$mid = intval(($left + $right + 1) / 2);
if ($nums[$mid] < $target) {
$left = $mid;
} else {
$right = $mid - 1;
}
}
return $left;
}
}
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
class Solution {
function addDigits($num) {
$digital_root = 0
while ($num > 0) {
$digital_root += $num % 10
$num = intdiv($num, 10)
if ($num == 0 && $digital_root > 9) {
$num = $digital_root
$digital_root = 0
}
}
return $digital_root
}
}
Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]
class Solution {
function construct_paths($root, $path, &$paths) {
if ($root !== null) {
$path .= $root->val;
if ($root->left === null && $root->right === null) {
$paths[] = $path;
} else {
$path .= "->";
$this->construct_paths($root->left, $path, $paths);
$this->construct_paths($root->right, $path, $paths);
}
}
}
function binaryTreePaths($root) {
$paths = [];
$this->construct_paths($root, "", $paths);
return $paths;
}
}
Input: costs = [[17,2,17],[16,16,5],[14,3,19]]
Output: 10
Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue.
Minimum cost: 2 + 5 + 3 = 10.
class Solution {
function minCost($costs) {
$n = count($costs);
$dp = array_fill(0, $n, array_fill(0, 3, 0));
$dp[0] = $costs[0];
for ($i = 1; $i < $n; $i++) {
$dp[$i][0] = $costs[$i][0] + min($dp[$i-1][1], $dp[$i-1][2]);
$dp[$i][1] = $costs[$i][1] + min($dp[$i-1][0], $dp[$i-1][2]);
$dp[$i][2] = $costs[$i][2] + min($dp[$i-1][0], $dp[$i-1][1]);
}
return min($dp[$n-1][0], $dp[$n-1][1], $dp[$n-1][2]);
}
}
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
class TrieNode {
public $children;
public $word;
public function __construct() {
$this->children = [];
$this->word = null;
}
}
class Solution {
private $board;
private $result;
public function findWords($board, $words) {
$root = $this->buildTrie($words);
$this->board = $board;
$this->result = [];
for ($row = 0; $row < count($board); ++$row) {
for ($col = 0; $col < count($board[0]); ++$col) {
if (isset($root->children[$board[$row][$col]])) {
$this->backtrack($row, $col, $root);
}
}
}
return $this->result;
}
private function buildTrie($words) {
$root = new TrieNode();
foreach ($words as $word) {
$node = $root;
for ($i = 0; $i < strlen($word); ++$i) {
$letter = $word[$i];
if (!isset($node->children[$letter])) {
$node->children[$letter] = new TrieNode();
}
$node = $node->children[$letter];
}
$node->word = $word;
}
return $root;
}
private function backtrack($row, $col, $parent) {
$letter = $this->board[$row][$col];
$currNode = $parent->children[$letter];
if ($currNode->word !== null) {
$this->result[] = $currNode->word;
$currNode->word = null;
}
$this->board[$row][$col] = '#';
$rowOffset = [-1, 0, 1, 0];
$colOffset = [0, 1, 0, -1];
for ($i = 0; $i < 4; ++$i) {
$newRow = $row + $rowOffset[$i];
$newCol = $col + $colOffset[$i];
if (
$newRow >= 0 && $newRow < count($this->board) &&
$newCol >= 0 && $newCol < count($this->board[0])
) {
if (isset($currNode->children[$this->board[$newRow][$newCol]])) {
$this->backtrack($newRow, $newCol, $currNode);
}
}
}
$this->board[$row][$col] = $letter;
if (empty($currNode->children)) {
unset($parent->children[$letter]);
}
}
}
// Example usage:
$solution = new Solution();
$board = [
['o', 'a', 'a', 'n'],
['e', 't', 'a', 'e'],
['i', 'h', 'k', 'r'],
['i', 'f', 'l', 'v']
];
$words = ["oath", "pea", "eat", "rain"];
print_r($solution->findWords($board, $words));
Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]
Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
class TrieNode {
public $children;
public $isWord;
public function __construct() {
$this->children = [];
$this->isWord = false;
}
}
class WordDictionary {
private $root;
public function __construct() {
$this->root = new TrieNode();
}
public function addWord($word) {
$node = $this->root;
for ($i = 0; $i < strlen($word); $i++) {
$ch = $word[$i];
if (!isset($node->children[$ch])) {
$node->children[$ch] = new TrieNode();
}
$node = $node->children[$ch];
}
$node->isWord = true;
}
private function searchInNode($word, $node) {
for ($i = 0; $i < strlen($word); $i++) {
$ch = $word[$i];
if (!isset($node->children[$ch])) {
if ($ch === '.') {
foreach ($node->children as $child) {
if ($this->searchInNode(substr($word, $i + 1), $child)) {
return true;
}
}
}
return false;
} else {
$node = $node->children[$ch];
}
}
return $node->isWord;
}
public function search($word) {
return $this->searchInNode($word, $this->root);
}
}
Input: preorder = [5,2,1,3,6]
Output: true
class Solution {
function verifyPreorder($preorder) {
$minLimit = -PHP_INT_MAX;
$stack = [];
foreach ($preorder as $num) {
while (!empty($stack) && end($stack) < $num) {
$minLimit = array_pop($stack);
}
if ($num <= $minLimit) {
return false;
}
$stack[] = $num;
}
return true;
}
}
Input: n = 1
Output: []
class Solution {
private function backtracking(&$factors, &$ans) {
if (count($factors) > 1) {
$ans[] = $factors;
}
$lastFactor = array_pop($factors);
$start = empty($factors) ? 2 : end($factors);
for ($i = $start; $i * $i <= $lastFactor; ++$i) {
if ($lastFactor % $i == 0) {
$factors[] = $i;
$factors[] = $lastFactor / $i;
$this->backtracking($factors, $ans);
array_pop($factors);
array_pop($factors);
}
}
$factors[] = $lastFactor;
}
public function getFactors($n) {
$ans = [];
$factors = [$n];
$this->backtracking($factors, $ans);
return $ans;
}
}
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
class Solution {
function minMeetingRooms($intervals) {
usort($intervals, function($a, $b) {
return $a[0] - $b[0];
});
$heap = new SplMinHeap();
$heap->insert($intervals[0][1]);
for ($i = 1; $i < count($intervals); $i++) {
if ($intervals[$i][0] >= $heap->top()) {
$heap->extract();
}
$heap->insert($intervals[$i][1]);
}
return $heap->count();
}
}
Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
class Solution {
function overlap($interval1, $interval2) {
return ($interval1[0] >= $interval2[0] && $interval1[0] < $interval2[1]) ||
($interval2[0] >= $interval1[0] && $interval2[0] < $interval1[1]);
}
function canAttendMeetings($intervals) {
for ($i = 0; $i < count($intervals); $i++) {
for ($j = $i + 1; $j < count($intervals); $j++) {
if ($this->overlap($intervals[$i], $intervals[$j])) {
return false;
}
}
}
return true;
}
}
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Объяснение: Всего есть 4 курса, которые нужно пройти. Чтобы взять курс 3, вы должны завершить оба курса 1 и 2. Оба курса 1 и 2 должны быть взяты после того, как вы завершите курс 0.
Таким образом, один из правильных порядков курсов — [0,1,2,3]. Другой правильный порядок — [0,2,1,3].
class Solution {
const WHITE = 1;
const GRAY = 2;
const BLACK = 3;
public function findOrder($numCourses, $prerequisites) {
$isPossible = true;
$color = array_fill(0, $numCourses, self::WHITE);
$adjList = [];
$topologicalOrder = [];
foreach ($prerequisites as $relation) {
list($dest, $src) = $relation;
if (!isset($adjList[$src])) {
$adjList[$src] = [];
}
$adjList[$src][] = $dest;
}
for ($i = 0; $i < $numCourses && $isPossible; $i++) {
if ($color[$i] == self::WHITE) {
$this->dfs($i, $color, $adjList, $isPossible, $topologicalOrder);
}
}
if ($isPossible) {
$order = array_reverse($topologicalOrder);
return $order;
} else {
return [];
}
}
private function dfs($node, &$color, &$adjList, &$isPossible, &$topologicalOrder) {
if (!$isPossible) return;
$color[$node] = self::GRAY;
if (isset($adjList[$node])) {
foreach ($adjList[$node] as $neighbor) {
if ($color[$neighbor] == self::WHITE) {
$this->dfs($neighbor, $color, $adjList, $isPossible, $topologicalOrder);
} else if ($color[$neighbor] == self::GRAY) {
$isPossible = false;
}
}
}
$color[$node] = self::BLACK;
$topologicalOrder[] = $node;
}
}