[JavaScript] JavaScript 获取两个数组的交集 →→→→→进入此内容的聊天室

来自 , 2019-03-30, 写在 JavaScript, 查看 106 次.
URL http://www.code666.cn/view/a660d456
  1. /* finds the intersection of
  2.  * two arrays in a simple fashion.  
  3.  *
  4.  * PARAMS
  5.  *  a - first array, must already be sorted
  6.  *  b - second array, must already be sorted
  7.  *
  8.  * NOTES
  9.  *
  10.  *  Should have O(n) operations, where n is
  11.  *    n = MIN(a.length(), b.length())
  12.  */
  13. function arrayIntersection(a, b)
  14. {
  15.   var ai=0, bi=0;
  16.   var result = new Array();
  17.  
  18.   while( ai < a.length && bi < b.length )
  19.   {
  20.      if      (a[ai] < b[bi] ){ ai++; }
  21.      else if (a[ai] > b[bi] ){ bi++; }
  22.      else /* they're equal */
  23.      {
  24.        result.push(a[ai]);
  25.        ai++;
  26.        bi++;
  27.      }
  28.   }
  29.  
  30.   return result;
  31. }
  32.  
  33. console.log(arrayIntersection([1,2,3],[2,3,4,5,6]));//[2,3]
  34. //javascript/4325

回复 "JavaScript 获取两个数组的交集"

这儿你可以回复上面这条便签

captcha