【问题标题】:Finding the lonely integer - JavaScript寻找孤独的整数 - JavaScript
【发布时间】:2022-06-16 02:02:16
【问题描述】:

考虑数组 [1,2,2]

数组包含两个唯一值:1、2

数组包含重复值:2

孤独的整数是1

孤独的整数如何返回?

【问题讨论】:

  • 如果有超过1个“孤独”整数?会全部退回吗?
  • 嘿,@PeterKA,是的,这就是目标。

标签: javascript arrays filter indexof


【解决方案1】:

工作演示:

// Array with duplicates
const arrWithDuplicates = [1, 2, 2];
 
var result = arrWithDuplicates.sort().filter((x,i,arr) => x !== arr[i+1] && x !== arr[i-1]);
console.log(result); // [1]

【讨论】:

【解决方案2】:

对于只关心获取第一个孤立整数的数组,您可以检查 indexOf 和 lastIndexOf 是否相同。如果是,那就是寂寞了。

const array = [2, 2, 1, 3, 4, 3, 4];

const findLonely = (arr) => {
    for (const num of arr) {
        if (arr.indexOf(num) === arr.lastIndexOf(num)) return num;
    }
    return 'No lonely integers.';
};

console.log(findLonely(array));

如果您有一个包含多个孤独值的数组,则可以使用此方法查找所有孤独值:

const array = [2, 2, 1, 3, 4, 3, 4, 6, 8, 8, 9];

const findAllLonely = (arr) => {
    const map = {};

    arr.forEach((num) => {
        // Keep track of the number of time each number appears in the array
        if (!map[num]) return (map[num] = 1);
        map[num]++;
    });

    // Filter through and only keep the values that have 1 instance
    return Object.keys(map).filter((key) => {
        return map[key] === 1;
    });
};

console.log(findAllLonely(array)); // expect [1, 6, 9]

【讨论】:

  • 这是一个更好的方法。我很感激反馈。谢谢!
  • @MikeySherm 没问题))如果你发现自己为这么简单的事情写了 3 个循环,那么重新评估通常是个好主意哈哈。
【解决方案3】:

对于每个元素,您可以使用.filter() 来帮助计算元素重复的次数。然后再次使用.filter(),只返回那些出现过一次的元素。

const nums = [1,2,2,3,4,4,4,5,5,6,7,7,7,8,8];

const singles = nums.filter(
    //count how many times each element appears
    num => nums.filter(n => n === num)
    //return only those with freq. of 1
    .length === 1
);

console.log( singles );
//OUTPUT: [  1,  3,  6 ]

【讨论】:

    【解决方案4】:

    使用带有过滤器函数的'for'循环来循环遍历数组并且只返回出现一次的值

    const arr = [0, 1, 2, 2, 1];
    let unique;
    
    for(var i = 0; i < arr.length; i++) {
        if(a.filter(x => x == arr[i]).length == 1) {
            unique = arr[i]
        }
    }
    
    return unique;
    

    【讨论】:

      【解决方案5】:
      function lonelyinteger(a) {
          for (let i = 0; i < a.length; i++) {
              const count = a.filter((v) => v === a[i]).length;
              if (count === 1) {
                  console.log(a[i]);
                  return a[i];
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-19
        • 2012-01-31
        • 1970-01-01
        • 2011-05-05
        • 1970-01-01
        • 2012-11-26
        • 1970-01-01
        • 2021-12-25
        相关资源
        最近更新 更多