【问题标题】:Find element that appears odd number of times查找出现奇数次的元素
【发布时间】:2017-09-13 14:30:04
【问题描述】:

我正在尝试解决这个寻找在数组中出现奇数次的数字的练习。到目前为止我有这个,但输出最终是一个出现偶数次的整数。例如,数字 2 出现了 3 次,数字 4 出现了 6 次,但输出是 4,因为它把它算作出现了 5 次。它怎么会返回它发现为奇数的第一个集合?任何帮助表示赞赏!

         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 <array.length; j++) {
                if(array[j]===tempInt) {
                tempCount++;
                  if(tempCount % 2 !== 0 && tempCount > count) {
                  count = tempCount; 
                  element = array[j];
                }
               }
              }
             }
           return element;
           }
           oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);

【问题讨论】:

  • 你想要所有奇数还是只有一个?
  • 只有一个值!感谢回复
  • 您有 3 个问题和 0 个接受的答案。接受答案的比率低会使用户无法帮助您,因为您不会奖励我们为他们付出的努力。

标签: javascript arrays for-loop integer


【解决方案1】:

function findOdd(numbers) {
  var count = 0;
  for(var i = 0; i<numbers.length; i++){
    for(var j = 0; j<numbers.length; j++){
      if(numbers[i] == numbers[j]){
        count++;
      }
    }
    if(count % 2 != 0 ){
      return numbers[i];
    }
  }
};

console.log(findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5])); //5
console.log(findOdd([1,1,1,1,1,1,10,1,1,1,1])); //10

【讨论】:

    【解决方案2】:

    先找频率,再找奇数:

    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"]
    

    【讨论】:

    • 你能进一步解释一下吗?看起来很简洁
    • @GelSisaed 在freq 表达式中,我们获取项目数组并将其折叠到频率字典中(其中键是原始项目,值是项目出现的次数)。然后我们过滤掉这个字典中对应值为奇数的键。
    • 感谢@Asad。 es6 语法使它更短,如果不了解一点 es6,我将无法理解它。这一行 ({ ...o, [k]: (o[k] || 0) + 1 }) 创建字典正确吗?
    • @GelSisaed 对,它采用现有字典o,并添加另一个键k,其值为(o[k] || 0) + 1(即如果k 存在于o 中,则加1 ,否则为 1 + 0)。
    【解决方案3】:

    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]));

    只返回第一个:

    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]));

    【讨论】:

      【解决方案4】:

      这是一个 O(N) 或 O(N*log(N)) 的解决方案

      function findOdd(A) {
          var count = {};
          for (var i = 0; i < A.length; i++) {
              var num = A[i];
              if (count[num]) {
                  count[num] = count[num] + 1;
              } else {
                  count[num] = 1;
              }
          }
          var r = 0;
          for (var prop in count) {
              if (count[prop] % 2 != 0) {
                  r = prop;
              }
          }
          return parseInt(r); // since object properies are strings
      }
      

      【讨论】:

        【解决方案5】:

        发生这种情况是因为您在每次找到奇数时设置element 变量,因此在找到一、三和五4 时设置它。

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

        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 <array.length; j++) {
                    // If the current number is the same as the one that we are looking for, sum it up
                    console.log("Current number at position", j, "is", array[j]);
                    if(array[j]===tempInt) {
                        tempCount++;
                        console.log("Number found. Current count is", tempCount);
                        // Then, if currently there are an odd number of elements, save the number
                        // Note that you are calling this altough you don't have looped throgh all the array, so the console will log 3 and 5 for the number '4'
                        if(tempCount % 2 !== 0 && tempCount > 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]);
        

        我们要做的是在循环所有数组之后检查计数,这样:

        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 <array.length; j++) {
                    // If the current number is the same as the one that we are looking for, sum it up
                    console.log("Current number at position", j, "is", array[j]);
                    if(array[j]===tempInt) {
                        tempCount++;
                        console.log("Number found. Current count is", tempCount);
                    }
                }
                // After getting all the numbers, then we check the count
                if(tempCount % 2 !== 0 && tempCount > 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]);
        

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

        【讨论】:

        • 非常感谢!真的有帮助!
        【解决方案6】:

        如果我们确定只有一个数字会出现奇数次,我们可以对这些数字进行异或运算,并在 n 次比较中找到出现奇数次的数字。如果两位不同,则异或为 1,否则为 0。真值表如下。

        A   B   A^B
        0   0    0
        0   1    1
        1   0    1
        1   1    0
        

        因此,当我们对所有数字进行异或运算时,最终数字将是出现奇数次的数字。 让我们取一个数字并将其与相同的数字进行异或(出现两次)。结果将为 0,因为所有位都相同。现在让我们用相同的数字对结果进行 XOR。现在结果将是那个数字,因为先前结果的所有位都是 0,并且只有相同数字的设置位将在结果中设置。现在将其扩展为包含 n 个数字的数组,出现偶数次的数字将给出结果 0。出现奇数的数字会在最终结果中产生该数字。

        func oddInt(numbers: [Int]) -> Int {
        var result = 0
        for aNumber in numbers {
          result = result ^ aNumber
        }
        return result
        }
        

        【讨论】:

          【解决方案7】:
           #using python
           a=array('i',[1,1,2,3,3])
           ans=0
           for i in a:
               ans^=i
           print('The element that occurs odd number of times:',ans)
           
            
          
           
          
          1. 列表项 输出:

            出现奇数次的元素:2

            Xor(^) 操作符,当有奇数个 1 时,我们可以在输出中得到一个 1
            参考异或真值表: https://www.electronicshub.org/wp-content/uploads/2015/07/TRUTH-TABLE-1.jpg

          【讨论】:

            【解决方案8】:

            这是因为当检查第5次4时,您的条件if(tempCount % 2 !== 0 &amp;&amp; tempCount &gt; count)是真的。这将更新 count 和 element 变量。

            选中第6个4时,条件为假。

            要解决此问题,请将条件移到最内层循环之外,以便仅在计算完数组中的所有数字后才对其进行检查。

            【讨论】:

            • 感谢您的回复!你认为你可以展示如何格式化吗?
            • 感谢您的建议。豪尔赫·冈萨雷斯(Jorge Gonzales)对此进行了详细说明。欣赏!
            【解决方案9】:

            function oddInt(array, minCount, returnOne) {
              minCount = minCount || 1;
              var itemCount = array.reduce(function(a, b) {
                a[b] = (a[b] || 0) + 1;
                return a;
              }, {});
              /*
              itemCount: {
                "1": 1,
                "2": 3,
                "4": 6,
                "5": 2,
                "7": 3
              }
              */
              var values = Object.keys(itemCount).filter(function(k) {
                return itemCount[k] % 2 !== 0 && itemCount[k]>=minCount;
              });
              
              return returnOne?values[0]:values;
            }
            
            var input = [1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5, 7, 7, 7];
            
            console.log(oddInt(input, 3, true));
            console.log(oddInt(input, 1, true));
            console.log(oddInt(input, 2, false));

            【讨论】:

              【解决方案10】:

              “A”是要检查的数组。

              function findOdd(A) {
                  var num;
                  var count =0;
                  for(i=0;i<A.length;i++){
                     num = A[i]
                     for(a=0;a,a<A.length;a++){
                        if(A[a]==num){
                        count++;
                        }
                   } if(count%2!=0){
                        return num;
                   }
                 }
              }
              

              【讨论】:

                【解决方案11】:
                function oddOne (sorted) {
                  let temp = sorted[0];
                  let count = 0;
                  for (var i = 0; i < sorted.length; i++) {
                    if (temp === sorted[i]) {
                      count++;
                      if (i === sorted.length - 1) {
                        return sorted[i];
                      }
                    } else {
                      if (count % 2 !== 0) {
                        return temp;
                      }
                
                      count = 1;
                      temp = sorted[i];
                    }
                  }
                }
                

                【讨论】:

                  【解决方案12】:
                  function oddInt(array) {
                      let result = 0;
                      for (let element of array) {
                          result ^= element
                      }
                      return result
                  }
                  

                  【讨论】:

                  • 虽然此代码可以解决 OP 的问题,但最好包含关于您的代码如何解决 OP 问题的说明。这样,未来的访问者可以从您的帖子中学习,并将其应用到他们自己的代码中。 SO 不是编码服务,而是知识资源。此外,高质量、完整的答案更有可能获得支持。这些功能,以及所有帖子都是独立的要求,是 SO 作为一个平台的一些优势,使其与论坛区分开来。您可以编辑以添加其他信息和/或使用源文档补充您的解释。
                  【解决方案13】:
                  var oddNumberTimes = (arr) => {
                    let hashMap = {};
                  
                    for (let i = 0; i < arr.length; i++) {
                      hashMap[arr[i]] = hashMap[arr[i]] + 1 || 1;
                    }
                  
                    for (let el in hashMap) {
                      if (hashMap[el] % 2 !== 0) {
                        return el;
                      }
                    }
                  
                    return -1;
                  };
                  

                  【讨论】:

                  • 如果能添加一些解释对以后访问该问题的人有帮助会更好
                  【解决方案14】:

                  您可以使用按位异或:

                  function oddInt(array) {
                    return array.reduce(function(c, v) {
                      return c ^ v;
                    }, 0);
                  }
                  console.log(oddInt([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]) == 5);
                  console.log(oddInt([1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1]) == 10);

                  【讨论】:

                    【解决方案15】:

                    var arr=[1,2,2,2,2,3,4,3,3,3,4,5,5,9,9,10];

                    var arr1=[];

                    for(让 i=0;i

                     {
                        var count=0;
                    
                        for(let j=0;j<arr.length;j++)
                    
                         {
                            if(arr[i]==arr[j])
                    
                            {
                    
                               count++;
                            }
                          }
                    
                         if(count%2 != 0 )
                    
                            {
                    
                               arr1.push(arr[i]);
                             }
                      }
                    

                    console.log(arr1);

                    【讨论】:

                    • 对于上半循环,在该计数之后是“for(let i=0;i
                    • 请看下面是否正确这是否意味着您提供了未经测试的答案?顺便说一句,不要只发布代码,而是要解释。
                    • dude 通俗易懂,提供的解决方案经过测试,相信新手也能看懂
                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2023-03-19
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-04-17
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多