簡體   English   中英

比較兩個數組中元素的相等性

[英]Comparing equality of elements in two arrays

我有一個任務,我應該用整數檢查兩個數組(未排序),看看是否

  1. 它們的長度相同
  2. 第一個元素包含整數,第二個元素以任何順序具有相同的平方值

例如:

test([5,4,1], [1,16,25]) // would return true ..

到目前為止我所做的是首先對兩個輸入數組進行排序,然后比較長度。 一旦我們確認長度是相同的,我們迭代每個值以確保它們是相等的。 請記住,我還沒有將值與它們的平方對應物進行比較,因為我的循環沒有給出預期的結果。 這是代碼:

function test(arr1, arr2){
  // sort arrays
  const arr1Sort = arr1.sort(),
        arr2Sort = arr2.sort();

  // compare length and then compare values
  if(arr1Sort.length === arr2Sort.length) {
    for(let i = 0; i < arr1Sort.length; i++) {
      if(arr1Sort[i] === arr2Sort[i]) {
        return true;
      } else {
        return false;
      }
    }
  }
}

console.log(test([1,2,3], [1,5,4])); returns true but the array values are different?!

for ,無論是否滿足ifelse函數將在第一次迭代時立即返回truefalse - 它永遠不會超過索引0 首先, return true循環已經結束后才return false如果arr1Sort[i] ** 2 !== arr2Sort[i]以檢查第一平方等於第二)。

此外,在排序時,請確保使用回調函數來比較每個項目的差異 ,否則, .sort將按字母順序排序(例如, [1, 11, 2] 1,11,2 [1, 11, 2] ):

 function comp(arr1, arr2){ // sort arrays const sortCb = (a, b) => a - b; const arr1Sort = arr1.sort(sortCb), arr2Sort = arr2.sort(sortCb); // compare length and then compare values if(arr1Sort.length !== arr2Sort.length) { return false; } for(let i = 0; i < arr1Sort.length; i++) { if(arr1Sort[i] ** 2 !== arr2Sort[i]) { return false; } } return true; } console.log(comp([1,2,3], [1,5,4])); console.log(comp([5,4,1], [1,16,25])); 

您可以通過將arr2轉換為預先由平方數索引的對象,將計算復雜度降低到O(N)而不是O(N log N)

 function comp(arr1, arr2){ if (arr1.length !== arr2.length) { return false; } const arr2Obj = arr2.reduce((a, num) => { a[num] = (a[num] || 0) + 1; return a; }, {}); for (let i = 0; i < arr1.length; i++) { const sq = arr1[i] ** 2; if (!arr2Obj[sq]) { return false; } arr2Obj[sq]--; } return true; } console.log(comp([1,2,3], [1,5,4])); console.log(comp([5,4,1], [1,16,25])); 

(如果不允許重復,那么使用Set會更容易,但不幸的是,它們很簡單)

這應該工作,無需比較數據:

 function similar(needle, haystack, exact){ if(needle === haystack){ return true; } if(needle instanceof Date && haystack instanceof Date){ return needle.getTime() === haystack.getTime(); } if(!needle || !haystack || (typeof needle !== 'object' && typeof haystack !== 'object')){ return needle === haystack; } if(needle === null || needle === undefined || haystack === null || haystack === undefined || needle.prototype !== haystack.prototype){ return false; } var keys = Object.keys(needle); if(exact && keys.length !== Object.keys(haystack).length){ return false; } return keys.every(function(k){ return similar(needle[k], haystack[k]); }); } console.log(similar(['a', {cool:'stuff', yes:1}, 7], ['a', {cool:'stuff', yes:1}, 7], true)); // not exact console.log(similar(['a', {cool:'stuff', yes:1}, 7], ['a', {cool:'stuff', stuff:'more', yes:1}, 7, 'more stuff only at the end for numeric array'])); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM