& Lt; C # & gt; find the maximum number of duplicates in the array

Source: Internet
Author: User

<C #> Find the maximum number of duplicates in the array.
Given an int array, there are repeated values. How can we find the maximum number of duplicates? This is a question raised by someone in a community. The solution I think of is grouping. 1. group all elements in the array first. Repeated values are certainly placed in a group. 2. Sort groups by the number of elements in the group; 3. The group with the largest number of elements has the largest number of duplicates. Based on the above ideas, you can write the following code: copy the code // sample array, 90 repeats for 4 times, 1 repeats for 2 times, 3 repeats for 3 times int [] arr = {1, 1, 3, 3, 3, 7, 50, 15, 15, 90, 90, 90, 90,105};/** groups all elements of the array first, * sort the number of elements in each group in descending order */var res = from n in arr group n by n into g orderby g. count () descending select g; // The first group in the group is the var gr = res. first (); foreach (int x in gr) {Console. write ("{0}", x);} in the sample array, 1 appears twice, 3 appears three times, 15 appears twice, and 90 appears four times. Obviously, the maximum number of repetitions is 90. Use the Linq statement to group all elements in the source array according to the elements themselves. Then, use the Count method to calculate the number of elements in each group and sort them in descending order. In the first group in the result, the elements in the group are naturally the most repeated. Due to my limited personal character value, I can only come up with this simple method to deal with it. audience members, if you have a simpler method, be sure to post it and don't say "Jin Wu Zang Jiao ".

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.