查找数组中没有对的数字 [英] find number with no pair in array

查看:35
本文介绍了查找数组中没有对的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一小段代码,这是一个随机大小的数组,带有随机数对,但是没有一对.

I am having trouble with a small bit of code, which in a random size array, with random number pairs, except one which has no pair.

我需要找到没有对的那个号码.

I need to find that number which has no pair.

arLength是数组的长度.但我在实际匹配线对时遇到了麻烦,并找到了没有线对的那个..

arLength is the length of the array. but i am having trouble actually matching the pairs, and finding the one which has no pair..

 for (int i = 0; i <= arLength; i++)
        { // go through the array one by one..
            var number = nArray[i];

            // now search through the array for a match.
            for (int e = 0; e <= arLength; e++)
            {
                if (e != i)
                {

                }
            }
        }

我也尝试过:

var findValue = nArray.Distinct();

我已经搜索过了,但是到目前为止,我还没有找到解决这个问题的方法.

I have searched around, but so far, i haven't been able to find a method for this.

这是生成数组的代码,但是这个问题不是关于代码的这一部分,只是为了清楚起见.

This code is what generates the array, but this question isn't about this part of the code, only for clarity.

Random num = new Random();
            int check = CheckIfOdd(num.Next(1, 1000000));
            int counter = 1;

            while (check <= 0)
            {
                if (check % 2 == 0)
                {
                    check = CheckIfOdd(num.Next(1, 1000000)); ;
                }
                counter++;
            }
            int[] nArray = new int[check];
            int arLength = 0;
            //generate arrays with pairs of numbers, and one number which does not pair.
            for (int i = 0; i < check; i++)
            {
                arLength = nArray.Length;

                if (arLength == i + 1) 
                {
                    nArray[i] = i + 1;
                }
                else
                {
                    nArray[i] = i;
                    nArray[i + 1] = i;
                }
                i++;
            }

推荐答案

Distict 将为您提供具有不同值的数组.它不会找到您需要的值.

Distict will give you back the array with distinct values. it will not find the value you need.

您可以 GroupBy 并选择 Count 模2等于1的值.

You can GroupBy and choose the values with Count modulo 2 equals 1.

var noPairs = nArray.GroupBy(i => i)
                    .Where(g => g.Count() % 2 == 1)
                    .Select(g=> g.Key);

这篇关于查找数组中没有对的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆