Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Найти пересечения двух массивов
- если на входе массивы отсортированы решение через два указателя
- */
- // Хеш таблица
- function intersection(nums1, nums2) {
- let result = [];
- let hash = {};
- for (let num of nums1) {
- hash[num] = (hash[num] || 0) + 1;
- }
- for (let num of nums2) {
- if (num in hash && hash[num] > 0) {
- result.push(num);
- hash[num]--;
- }
- }
- return result;
- }
- // два указателя
- function intersection1(nums1, nums2) {
- let sortFn = (a, b) => a - b;
- // Вариант решения, если массивы не отсортированы
- nums1.sort(sortFn);
- nums2.sort(sortFn);
- let m = nums1.length;
- let n = nums2.length;
- let i = 0;
- let j = 0;
- let result = [];
- while (i < m && j < n) {
- if (nums1[i] === nums2[j]) {
- result.push(nums1[i]);
- i++;
- j++;
- } else if (nums1[i] < nums2[j]) {
- i++;
- } else {
- j++;
- }
- }
- return result;
- }
- console.log(intersection([1, 2, 3, 2, 0],[5, 1, 2, 7, 3, 2] ))
- console.log(intersection1([1, 2, 3, 2, 0],[5, 1, 2, 7, 3, 2] ))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement