Skip to content

Instantly share code, notes, and snippets.

@YozhEzhi
Created July 30, 2018 20:25
Show Gist options
  • Select an option

  • Save YozhEzhi/ebe1006e34fecfdef4421d9982197dd2 to your computer and use it in GitHub Desktop.

Select an option

Save YozhEzhi/ebe1006e34fecfdef4421d9982197dd2 to your computer and use it in GitHub Desktop.
Алгоритмы. Поиск не уникального элемента в массиве.
function repeatedItem {
  for (let i = 0; i < array.length; i++) {
    for (let j = i + 1; j < array.length; j++) {
      if (array[i] === array[j]) return array[i];
    }
  }
}

This implementation does work fine. However due to the two loops the worst case runtime is of the order , where n is the length of the array.

function repeatedItem {
  const set = new Set();
  for (const item of array) {
    if (set.has(item)) {
      return item;
    } else {
      set.add(item);
    }
  }
}

Since we only loop through the items in the array once, doing constant work in each loop thanks to the set data structure, the runtime now falls to the order of n, where n is the length of the array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment