Home > Software design >  Swift compare arrays, anyone has an idea how to solve it?
Swift compare arrays, anyone has an idea how to solve it?

Time:11-27

Could someone tell me how I can solve this problem? I have two arrays in array 1 change values, array 2 has to synchronize with the first one, but without losing the value positions. I have tried with difference(from:) but it reorders the values of array 2. Here as it should be, thank you very much for your help.

let array1 = ["01", "06", "17", "22", "33", "45", "04"]
var array2 = ["04", "17", "22", "10", "01", "34"]

//
...
// Result
var array2 = ["04", "17", "22", "01", "06", "33", "45"]

The order of the values in array 2 must remain the same, delete those missing from array 1 and add those missing from array 1 to the end of array 2.

CodePudding user response:

Naive solution:

  1. Copy array1 to a temporary var `temp
  2. Loop through the indexes of temp in reverse order. If a value from temp exists in array2, remove it.
  3. Append temp to array2.

That would have poor (roughly O(n^2), or rather O(array1.count*array2.count)) time performance for large arrays, since the array contains() function is O(n). You could speed it up by using a set to track items in array2.

CodePudding user response:

This is the best solution I can get

  • Related