首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >查找出现奇数次的元素

查找出现奇数次的元素
EN

Stack Overflow用户
提问于 2017-04-18 06:16:05
回答 15查看 14K关注 0票数 4

我正在尝试解决寻找在数组中出现奇数次的数字的练习。到目前为止,我已经得到了这个结果,但是输出结果是一个出现了偶数次的整数。例如,数字2出现3次,数字4出现6次,但输出是4,因为它将其视为出现5次。它怎么会返回它发现为奇数的第一个集合呢?如有任何帮助,我们将不胜感激!

代码语言:javascript
运行
复制
function oddInt(array) {
         var count = 0;
         var element = 0;
         for(var i = 0; i < array.length; i++) {
           var tempInt = array[i];
           var tempCount = 0;
             for(var j = 0; j  count) {
                  count = tempCount; 
                  element = array[j];
                }
               }
              }
             }
           return element;
           }
           oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);
EN

回答 15

Stack Overflow用户

发布于 2018-08-23 16:25:14

代码语言:javascript
运行
复制
function findOdd(numbers) {
  var count = 0;
  for(var i = 0; i

票数 7
EN

Stack Overflow用户

发布于 2017-08-21 10:07:53

首先找出频率,然后找出哪些是奇数:

代码语言:javascript
运行
复制
const data = [1,2,2,2,4,4,4,4,4,4,5,5]
const freq = data.reduce(
  (o, k) => ({ ...o, [k]: (o[k] || 0) + 1 }), 
  {})
const oddFreq = Object.keys(freq).filter(k => freq[k] % 2)

// => ["1", "2"]
票数 4
EN

Stack Overflow用户

发布于 2017-04-18 06:26:47

代码语言:javascript
运行
复制
function oddInt(array) {
  // first: let's count occurences of all the elements in the array
  var hash = {};                 // object to serve as counter for all the items in the array (the items will be the keys, the counts will be the values)
  array.forEach(function(e) {    // for each item e in the array
    if(hash[e]) hash[e]++;       // if we already encountered this item, then increments the counter
    else hash[e] = 1;            // otherwise start a new counter (initialized with 1)
  });
  
  // second: we select only the numbers that occured an odd number of times
  var result = [];               // the result array
  for(var e in hash) {           // for each key e in the hash (the key are the items of the array)
    if(hash[e] % 2)              // if the count of that item is an odd number
      result.push(+e);           // then push the item into the result array (since they are keys are strings we have to cast them into numbers using unary +)
  }
  return result;
}
console.log(oddInt([1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5]));

只返回第一个:

代码语言:javascript
运行
复制
function oddInt(array) {
  var hash = {};
  array.forEach(function(e) {
    if(hash[e]) hash[e]++;
    else hash[e] = 1;
  });
  
  for(var e in hash) { // for each item e in the hash
    if(hash[e] % 2)    // if this number occured an odd number of times
      return +e;       // return it and stop looking for others
  }
  // default return value here
}
console.log(oddInt([1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5]));

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43460509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档