查找出现奇数次数的元素

时间:2017-04-17 22:16:05

标签: javascript arrays for-loop integer

我正在尝试解决这个练习,找出在数组中出现奇数次数的练习。到目前为止我有这个,但输出最终是一个出现偶数次的整数。例如,数字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]);

15 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

&#13;
&#13;
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]));
&#13;
&#13;
&#13;

仅返回第一个:

&#13;
&#13;
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]));
&#13;
&#13;
&#13;

答案 2 :(得分: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"]

答案 3 :(得分:0)

这是因为当检查第5个if(tempCount % 2 !== 0 && tempCount > count)时,您的条件4为真。这会更新countelement变量。

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

要修复,请将条件移到最里面的循环之外,这样只有在计算了数组中的所有数字后才能检查它。

答案 4 :(得分:0)

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

答案 5 :(得分:0)

之所以发生这种情况,是因为每次找到奇数时都会设置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]);

顺便说一下,这只是为了让你了解问题的位置并从中吸取教训,虽然这不是最优化的方法,因为你可能会注意到你正在寻找,比方说,数字{ {1}}三次,当你第一次得到你想要的输出时。如果表演是家庭作业的一部分,那么你应该考虑另一种方式:P

答案 6 :(得分:0)

“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;
     }
   }
}

答案 7 :(得分:0)

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

答案 8 :(得分:0)

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

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

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

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

答案 9 :(得分:0)

这是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
}

答案 10 :(得分:0)

function oddInt(array) {
    let result = 0;
    for (let element of array) {
        result ^= element
    }
    return result
}

答案 11 :(得分:0)

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;
};

答案 12 :(得分:0)

 #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

答案 13 :(得分:0)

您可以使用按位异或:

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

答案 14 :(得分:-1)

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

var arr1 = [];

for(let 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);