首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
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

Stack Overflow用户

发布于 2017-04-18 06:32:43

这是因为您正在设置element变量,所以当它找到1、3和5时,就会设置它4

让我们一步一步地检查代码:

代码语言:javascript
运行
复制
function oddInt(array) {
    // Set the variables. The count and the element, that is going to be the output
    var count = 0;
    var element = 0;

    // Start looking the array
    for(var i = 0; i < array.length; i++) {
        // Get the number to look for and restart the tempCount variable
        var tempInt = array[i];
        var tempCount = 0;
        console.log("");
        console.log(" * Looking for number", tempInt);
        // Start looking the array again for the number to look for
        for(var j = 0; j  count) {
                    console.log("Odd count found:", tempCount);
                    count = tempCount;
                    element = array[j];
                }
            }
        }
    }
    return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);

我们要做的是在循环所有数组后检查计数,用这种方式:

代码语言:javascript
运行
复制
function oddInt(array) {
    // Set the variables. The count and the element, that is going to be the output
    var count = 0;
    var element = 0;

    // Start looking the array
    for(var i = 0; i < array.length; i++) {
        // Get the number to look for and restart the tempCount variable
        var tempInt = array[i];
        var tempCount = 0;
        console.log("");
        console.log(" * Looking for number", tempInt);
        // Start looking the array again for the number to look for
        for(var j = 0; j  count) {
            console.log("Odd count found:", tempCount);
            count = tempCount;
            element = tempInt;
        }
    }
    return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);

顺便说一句,这只是为了让您了解问题出在哪里并从中学习,尽管这不是最优化的方法,因为您可能会注意到您正在寻找,比方说,数字2三次,当你第一次得到你想要的输出时。如果性能是家庭作业的一部分,那么你应该换一种方式思考:P

票数 1
EN
查看全部 15 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43460509

复制
相关文章

相似问题

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