
- Главная
- Каталог
- Интернет технологии
- JavaScript | LeetCode
JavaScript | LeetCode
Разбираем задачи с LeetCode на языке программирования JavaScript
Статистика канала
Input: name = "alex", typed = "aaleex"
Output: true{}
var isLongPressedName = function(name, typed) {
let i = 0, j = 0;
while (j < typed.length) {
if (i < name.length && name[i] === typed[j]) {
i++;
} else if (j === 0 || typed[j] !== typed[j - 1]) {
return false;
}
j++;
}
return i === name.length;
};{}
Ставь 👍 и забирай 📚 Базу знаний
Input: values = [1,2,3]
Output: 6{}
var minScoreTriangulation = function(values) {
const n = values.length;
const dp = Array.from({ length: n }, () => Array(n).fill(0));
for (let length = 2; length < n; length++) {
for (let i = 0; i < n - length; i++) {
const j = i + length;
dp[i][j] = Infinity;
for (let k = i + 1; k < j; k++) {
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k][j] + values[i] * values[j] * values[k]);
}
}
}
return dp[0][n - 1];
};{}
Ставь 👍 и забирай 📚 Базу знаний
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 {
threeSumSmaller(nums, target) {
nums.sort((a, b) => a - b)
let sum = 0
for (let i = 0; i < nums.length - 2; i++) {
sum += this.twoSumSmaller(nums, i + 1, target - nums[i])
}
return sum
}
twoSumSmaller(nums, startIndex, target) {
let sum = 0
for (let i = startIndex;{}
Ставь 👍 и забирай 📚 Базу знаний
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4{}
class Solution {
shortestPalindrome(s) {
const n = s.length;
const rev = s.split('').reverse().join('');
for (let i = 0; i < n; i++) {
if (s.substring(0, n - i) === rev.substring(i)) {
return rev.substring(0, i) + s;
}
}
return "";
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: nestedList = [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].{}
var NestedIterator = function(nestedList) {
this.stack = [];
this.flatten(nestedList);
};
NestedIterator.prototype.flatten = function(nestedList) {
for (let i = nestedList.length - 1; i >= 0; i--) {
this.stack.push(nestedList[i]);
}
};
NestedIterator.prototype.next = function() {
return this.stack.pop().getInteger();
};
NestedIterator.prototype.hasNext = function() {
while (this.stack.length > 0 && !this.stack[this.stack.length - 1].isInteger()) {
this.flatten(this.stack.pop().getList());
}
return this.stack.length > 0;
};{}
Ставь 👍 и забирай 📚 Базу знаний
Input: logs = [[0,2,0],[1,0,1],[3,0,3],[4,1,2],[7,3,1]], n = 4
Output: 3
Explanation: At timestamp = 3, all the persons (i.e., 0, 1, 2, and 3) become friends.{}
class UnionFind {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i)
this.rank = Array(n).fill(1)
}
find(x) {
if (this.parent[x] !== x) {
this.parent[x] = this.find(this.parent[x])
}
return this.parent[x]
}
union(x, y) {
const rootX = this.find(x)
const rootY = this.find(y)
if (rootX !== rootY) {
if (this.rank[rootX] > this.rank[rootY]) {
this.parent[rootY] = rootX
} else if (this.rank[rootX] < this.rank[rootY]) {
this.parent[rootX] = rootY
} else {
this.parent[rootY] = rootX
this.rank[rootX]++
}
return true
}
return false
}
}
var earliestAcq = function(logs, n) {
logs.sort((a, b) => a[0] - b[0])
const uf = new UnionFind(n)
let groupCount = n
for (const [timestamp, friendA, friendB] of logs) {
if (uf.union(friendA, friendB)) {
groupCount--
}
if (groupCount === 1) {
return timestamp
}
}
return -1
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: events= [[1,2],[2,3],[3,4],[1,2]]
Output: 4{}
var maxEvents = function(events) {
events.sort((a, b) => a[1] - b[1]);
let visitedDays = new Set();
let count = 0;
for (let [start, end] of events) {
for (let day = start; day <= end; day++) {
if (!visitedDays.has(day)) {
visitedDays.add(day);
count++;
break;
}
}
}
return count;
};{}
Ставь 👍 и забирай 📚 Базу знаний
Input: n = 12
Output: 21{}
class Solution {
swap(s, i0, i1) {
if (i0 === i1) return s;
let chars = s.split('');
[chars[i0], chars[i1]] = [chars[i1], chars[i0]];
return chars.join('');
}
constructor() {
this.list = [];
}
permute(a, l, r) {
if (l === r) {
this.list.push(a);
} else {
for (let i = l; i <= r; i++) {
a = this.swap(a, l, i);
this.permute(a, l + 1, r);
a = this.swap(a, l, i);
}
}
}
nextGreaterElement(n) {
let s = '' + n;
this.permute(s, 0, s.length - 1);
this.list.sort();
let index = this.list.indexOf(s);
if (index !== -1 && index < this.list.length - 1) {
let result = parseInt(this.list[index + 1]);
if (result <= 2147483647) {
return result;
}
}
return -1;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.{}
class Solution {
canFinish(numCourses, prerequisites) {
const indegree = new Array(numCourses).fill(0);
const adj = Array.from({ length: numCourses }, () => []);
for (const [a, b] of prerequisites) {
adj[b].push(a);
indegree[a]++;
}
const q = [];
for (let i = 0; i < numCourses; i++) {
if (indegree[i] === 0) {
q.push(i);
}
}
let nodesVisited = 0;
while (q.length > 0) {
const node = q.shift();
nodesVisited++;
for (const neighbor of adj[node]) {
indegree[neighbor]--;
if (indegree[neighbor] === 0) {
q.push(neighbor);
}
}
}
return nodesVisited === numCourses;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output: 3
Explanation: The paths that sum to 8 are shown.{}
var pathSum = function(root, sum) {
let count = 0
const k = sum
const h = new Map()
const preorder = (node, curr_sum) => {
if (!node) return
curr_sum += node.val
if (curr_sum === k) {
count++
}
count += (h.get(curr_sum - k) || 0)
h.set(curr_sum, (h.get(curr_sum) || 0) + 1)
preorder(node.left, curr_sum)
preorder(node.right, curr_sum)
h.set(curr_sum, h.get(curr_sum) - 1)
}
preorder(root, 0)
return count
}{}
Ставь 👍 и забирай 📚 Базу знанийОтзывы канала
Каталог Телеграм-каналов для нативных размещений
JavaScript | LeetCode — это Telegam канал в категории «Интернет технологии», который предлагает эффективные форматы для размещения рекламных постов в Телеграмме. Количество подписчиков канала в 9.3K и качественный контент помогают брендам привлекать внимание аудитории и увеличивать охват. Рейтинг канала составляет 5.3, количество отзывов – 0, со средней оценкой 0.0.
Вы можете запустить рекламную кампанию через сервис Telega.in, выбрав удобный формат размещения. Платформа обеспечивает прозрачные условия сотрудничества и предоставляет детальную аналитику. Стоимость размещения составляет 1258.74 ₽, а за 5 выполненных заявок канал зарекомендовал себя как надежный партнер для рекламы в TG. Размещайте интеграции уже сегодня и привлекайте новых клиентов вместе с Telega.in!
Вы снова сможете добавить каналы в корзину из каталога
Комментарий