и посмотреть медиа
JavaScript | LeetCode
и посмотреть медиа
LeetCode tasks and solutions in JavaScript. Ideal for interview preparation and improving algorithm skills.
LeetCode tasks and solutions in JavaScript. Ideal for interview preparation and improving algorithm skills.
AI bot for text-to-speech and voice cloning in Telegram. Create audio using neural network quickly and easily.
The channel is dedicated to solving LeetCode tasks in JavaScript. It contains code examples for popular algorithmic problems frequently encountered in interviews. The materials will help master data structures, sorting, dynamic programming, and other key topics. Suitable for junior and middle developers looking to improve their skills.
Задача: 477. Total Hamming Distance Сложность: medium Хэммингово расстояние между двумя целыми числами — это количество позиций, в которых соответствующие биты отличаются. Дан целочисленный массив nums, верните сумму Хэмминговых расстояний между всеми парами чисел в nums. Пример: Input: nums = [4,14,2] Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). The answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. 👨💻 Алгоритм: 1⃣Для каждой уникальной пары элементов из массива вычисляем битовое XOR, чтобы найти позиции, где биты различаются. Бит, равный 1 в результате, указывает на различие. 2⃣Для каждой пары элементов используем XOR, чтобы получить битовую разницу, и подсчитываем количество битов, равных 1, чтобы определить Хэммингово расстояние между парой. 3⃣Суммируем все Хэмминговы расстояния для всех пар, чтобы получить общую сумму Хэмминговых расстояний. 😎 Решение: function totalHammingDistance(nums) { let ans = 0; if (nums.length === 0) { return ans; } for (let i = 0; i < nums.length - 1; i++) { for (let j = i + 1; j < nums.length; j++) { ans += (nums[i] ^ nums[j]).toString(2).split('1').length - 1; } } return ans; } Ставь 👍 и забирай 📚 Базу знаний
Открыть канал и посмотреть медиаOnly registered users can share their opinion.
Be the first to share your impression of this resource!