Advertisement
vit134

Пересечения массивов (Яндекс)

Nov 9th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.     Найти пересечения двух массивов
  3.  
  4.     если на входе массивы отсортированы решение через два указателя
  5. */
  6.  
  7. // Хеш таблица
  8. function intersection(nums1, nums2) {
  9.   let result = [];
  10.   let hash = {};
  11.  
  12.   for (let num of nums1) {
  13.     hash[num] = (hash[num] || 0) + 1;
  14.   }
  15.  
  16.   for (let num of nums2) {
  17.     if (num in hash && hash[num] > 0) {
  18.       result.push(num);
  19.       hash[num]--;
  20.     }
  21.   }
  22.  
  23.   return result;
  24. }
  25.  
  26.  
  27. // два указателя
  28. function intersection1(nums1, nums2) {
  29.   let sortFn = (a, b) => a - b;
  30.  
  31.   // Вариант решения, если массивы не отсортированы
  32.   nums1.sort(sortFn);
  33.   nums2.sort(sortFn);
  34.    
  35.   let m = nums1.length;
  36.   let n = nums2.length;
  37.    
  38.   let i = 0;
  39.   let j = 0;
  40.  
  41.   let result = [];
  42.  
  43.   while (i < m && j < n) {
  44.     if (nums1[i] === nums2[j]) {
  45.       result.push(nums1[i]);
  46.       i++;
  47.       j++;
  48.     } else if (nums1[i] < nums2[j]) {
  49.       i++;
  50.     } else {
  51.       j++;
  52.     }
  53.   }
  54.  
  55.   return result;
  56. }
  57.  
  58. console.log(intersection([1, 2, 3, 2, 0],[5, 1, 2, 7, 3, 2] ))
  59. console.log(intersection1([1, 2, 3, 2, 0],[5, 1, 2, 7, 3, 2] ))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement