How can I select a unique element in the array?

泪湿孤枕 提交于 2020-01-25 06:47:27

问题


I'm trying to solve this task of finding the unique element inside an array. So far I managed to solve 95%, but I'm failing on 0. I get an error saying that expected 0 and got 1.

I should get //10, which it does, but after I'm failing the test online. For all other values it has passed.

Any ideas about how to solve this and what I'm missing here?

function findOne(arr) {
  let x = arr[0];
  for (let i of arr) {
    if (i === x) {
      continue;
    } else {
      x = i;
    }
    return x;
  }
}
console.log(findOne([3, 10, 3, 3, 3]));

回答1:


You can get all values that appear once, by using a map to count how many times each element has appeared. You can then reduce that map into an array of unique values:

const findUnique = arr => {
  const mapEntries = [...arr.reduce((a, v) => a.set(v, (a.get(v) || 0) + 1), new Map()).entries()]
  return mapEntries.reduce((a, v) => (v[1] === 1 && a.push(v[0]), a), [])
}

console.log(findUnique([3, 10, 3, 3, 3]))
console.log(findUnique([1, 2, 3, 2, 4]))
console.log(findUnique([4, 10, 4, 5, 3]))

If you don't care about multiple unique values, you can just sort the array and use logic, rather than checking every value, provided the array only contains 2 different values, and has a length greater than 2:

const findUnique = arr => {
  a = arr.sort((a, b) => a - b)
  if (arr.length < 3 || new Set(a).size === 1) return null
  return a[0] === a[1] ? a[a.length-1] : a[0]
}

console.log(findUnique([3, 10, 3, 3, 3]))
console.log(findUnique([3, 3, 1]))
console.log(findUnique([3, 1]))
console.log(findUnique([3, 3, 3, 3, 3]))



回答2:


I don't really understand your code. You start with the first value in the array, then you loop through the array, skipping anything that's the same, and then return the first one that's not the same. That won't find unique values, it'll just find the first value that doesn't equal the first value. So for instance, try it on the array [1,2,2,2,2] and you'll get a result of 2 instead of 1, even though that's clearly wrong.

Instead, you can create a map of each value and its incidence, then filter by the ones that equal 1 at the end.

function findOne(arr) {
    const incidences = arr.reduce((map, val) => {
      map[val] = (map[val] || 0) + 1;
      return map;
    }, {});
    const values = Object.keys(incidences);
    for (let i = 0; i < values.length; ++i) {
      if (incidences[values[i]] === 1) { return values[i]; }
    }
    return null;
}

EDIT The above won't preserve the type of the value (i.e. it'll convert it to a string always, even if it was originally a number). To preserve the type, you can use an actual Map instead of an object:

function findOne(arr) {
    const incidences = arr.reduce((map, val) => {
      map.set(val, (map.get(val) || 0) + 1);
      return map;
    }, new Map());
    const singletons = Array.from(incidences).filter(entry => entry[1] === 1);
    return singletons.map(singleton => singleton[0]);
}



回答3:


Consider the following:

Recall that a span = max - min + 1;

Let Partition P1 be span from 0..span-1;

Let Partition P2 be span from span..(2*span)-1:

Place a number in P1 if it is not in P2.

Place a number in P2 if it is already in P1.

Once the number is in P2, do not consider it again.

If a number is in P1 then it is unique.




回答4:


Your code is complex, Try this

function findOne(arr) {
  const uniqueItems = [];
  arr.forEach(item => {
    const sameItems = arr.filter(x => x === item);
    if (sameItems.length === 1) {
      uniqueItems.push(item);
    }
  });

  return uniqueItems;
}
console.log(findOne([0, 1, 1, 3, 3, 3, 4]));

I'm getting all unique items from passed array, It may have multiple unique item




回答5:


this is a way simpler and fast:

function findOne(arr) {
  const a = arr.reduce((acc, e) => {
    e in acc || (acc[e] = 0)
    acc[e]++
    return acc
  }, {})
  return Object.keys(a).filter(k => a[k] === 1)[0] || null
}


来源:https://stackoverflow.com/questions/58610213/how-can-i-select-a-unique-element-in-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!