на любом языке
function search(nums, target, searchMin) {
for (let iMin = 0, iMax = nums.length - 1; iMin <= iMax; ) {
const index = (iMin + iMax) / 2 | 0;
const num = nums[index];
if (num === target && num !== nums[index + (searchMin ? -1 : 1)]) {
return index;
} else if (num <= target - (searchMin ? 1 : 0)) {
iMin = index + 1;
} else {
iMax = index - 1;
}
}
return -1;
}
function searchMinMax(nums, target) {
const iMin = search(nums, target, true);
return iMin === -1
? []
: [ iMin, search(nums, target, false) ];
}
const firstNonRepeatingLetter = ([...str]) => Object
.values(str.reduce((acc, n, i) => ((acc[n.toLowerCase()] ??= [ 0, i, n ])[0]++, acc), {}))
.reduce((min, n) => (n[0] === 1 && n[1] < min[1] ? n : min), [ 0, Infinity, '' ])
.pop();
const firstNonRepeatingLetter = str =>
str.charAt(Array
.from(str.toLowerCase())
.findIndex((n, i, a) => a.indexOf(n) === a.lastIndexOf(n))
);
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
length = len(matrix)
for i in range(0, length // 2):
for j in range(i, length - i - 1):
matrix[i][j], \
matrix[j][length - i - 1], \
matrix[length - i - 1][length - j - 1], \
matrix[length - j - 1][i] \
= \
matrix[length - j - 1][i], \
matrix[i][j], \
matrix[j][length - i - 1], \
matrix[length - i - 1][length - j - 1]
const sumIntervals = intervals => intervals
.slice()
.sort((a, b) => a[0] - b[0])
.reduce((acc, n) => {
const top = acc.at(-1);
if (!top || top[1] < n[0]) {
acc.push([...n]);
} else if (top[1] < n[1]) {
top[1] = n[1];
}
return acc;
}, [])
.reduce((acc, n) => acc - n[0] + n[1], 0);
null
. В стек сохраняем индекс, под которым добавленная пара оказалась в массиве с результатами.null
на индекс встреченной скобки. Конечно, если в стеке что-то есть. Если стек пустой - значит, у встреченной закрывающей скобки не было соответствующей ей открывающей, добавляем в результирующий массив пару из null
и текущего индекса.function bracketIndices(str) {
const stack = [];
const result = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === '{') {
stack.push(result.push([ i, null ]) - 1);
} else if (str[i] === '}') {
if (stack.length) {
result[stack.pop()][1] = i;
} else {
result.push([ null, i ]);
}
}
}
return result;
}
bracketIndices('{}{{{}}}') // [[0,1],[2,7],[3,6],[4,5]]
bracketIndices('---}{{}{') // [[null,3],[4,null],[5,6],[7,null]]
bracketIndices('fuck off') // []
function clone(value) {
const clone = {};
const stack = [];
for (
let i = 0, source = [ [ '', value ] ], target = clone;
i < source.length || stack.length;
i++
) {
if (i === source.length) {
[ i, source, target ] = stack.pop();
} else {
const [ k, v ] = source[i];
const isObject = v instanceof Object;
target[k] = isObject ? v.constructor() : v;
if (isObject) {
stack.push([ i, source, target ]);
[ i, source, target ] = [ -1, Object.entries(v), target[k] ];
}
}
}
return clone[''];
}
function clone(value) {
const stack = [];
const clones = new Map;
const getClone = val => val instanceof Object
? (clones.has(val) || stack.push([ val, clones.set(val, val.constructor()).get(val) ]),
clones.get(val))
: val;
for (getClone(value); stack.length;) {
const [ source, target ] = stack.pop();
Object.entries(source).forEach(n => target[n[0]] = getClone(n[1]));
}
return getClone(value);
}
как правильнее всего будет это сделать?
function createTreeFromArray(arr, key, parentKey) {
const tree = Object.fromEntries(arr.map(n => [ n[key], { ...n } ]));
return Object.fromEntries(Object.entries(tree).filter(([ , n ]) => {
return !(tree[n[parentKey]] && ((tree[n[parentKey]].children ??= {})[n[key]] = n));
}));
}
const tree = createTreeFromArray(arr, 'uid', 'parentUID');
function generator($str, $params) {
$result = [];
if (count($params)) {
$key = key($params);
$values = is_array($params[$key]) ? $params[$key] : [ $params[$key] ];
unset($params[$key]);
foreach ($values as $val) {
array_push($result, ...generator(str_replace("{{$key}}", $val, $str), $params));
}
} else {
$result[] = $str;
}
return $result;
}
0
) и переполнения предыдущего разряда. Цифра разряда нового числа - младший разряд суммы (т.е., остаток от деления на 10
).function sum(a, b) {
const result = [];
for (
let i = ~-a.length, j = ~-b.length, overflow = 0;
i >= 0 || j >= 0 || overflow;
i--, j--
) {
const digit = (a[i] | 0) + (b[j] | 0) + overflow;
overflow = +(digit > 9);
result.push(digit % 10);
}
return result.reverse();
}
const point = { latitude: lat, longtitude: lon };
const closest = arr.reduce((closest, n) => {
const d = sphericalDistance(point, n);
return d < closest[1] ? [ n, d ] : closest;
}, [ null, Infinity ])[0];
function sphericalDistance(p1, p2) {
// https://en.wikipedia.org/wiki/Great-circle_distance
}
const getMinimumUniqueSum = arr => [...arr]
.sort((a, b) => a - b)
.reduce((acc, n) => (acc[1] += acc[0] = Math.max(acc[0] + 1, n), acc), [ -Infinity, 0 ])
.pop();
Если происходит перемещение элементов, то счетчик увеличивается на 3, потому что происходит 3 операции с элементами.
[ arr[j - 1], arr[j] ] = [ arr[j], arr[j - 1] ];
swap(arr, j - 1, j); // функция меняет местами элементы, но как именно - вам неизвестно
function merge(nums1, m, nums2, n) {
for (let i = m + n, i1 = m - 1, i2 = n - 1; i--;) {
nums1[i] = i2 < 0 || nums1[i1] > nums2[i2] ? nums1[i1--] : nums2[i2--];
}
}
const N = чему-то там равно;
for (let i = 1, num = 1; i <= N; i++) {
console.log(num);
if (i === (1 + num) * num / 2) {
num++;
}
}
for (let i = 1; i <= N; i++) {
console.log(Math.ceil((Math.sqrt(1 + 8 * i) - 1) / 2));
}