Question description
961. Find elements that repeat N times in an array of length 2N
Give you an array of integer nums that has the following properties:
- == 2 * n.
- nums contains n + 1 different elements
- There is exactly one element in nums repeated n times
Find and return the element that has been repeated n times.
Example 1:
enter:nums = [1,2,3,3] Output:3
Example 2:
enter:nums = [2,1,2,5,3,2] Output:2
Example 3:
enter:nums = [5,1,5,2,5,3,5,4] Output:5
hint:
2 <= n <= 5000
== 2 * n
0 <= nums[i] <= 10^4
nums consists of n + 1 different elements, and one of them is repeated exactly n times
Idea Analysis
Let’s review 2n+1 first:
Among the 2n+1 numbers, n+1 numbers are the same. Find the number with the most repeated times.
Die the same method. Each time you go through an element, check whether the element in your hand is the same. If the same count +1, different count -1, if there is no element in your hand, that is, when the count is 0, take the current element into your hand.
Now let’s look at this topic. If 2n elements follow the previous practice of dying together, and there will be no elements in your hands in the end, and they will all die together, then what should I do?
Since there is no 2n+1 scenario, we will try to create this situation
For example: [1,2,4,5,3,3,3,3] sequence
We divide the first element 1 as the element to be removed and divide the original array into two parts. [1,2] and [4,5,3,3,3,3] to use the same death method for the latter part of the sequence, will we get the result? !
Of course, some people will ask, what should I do if 1 is the result? For example, in this sequence [1,1,1,1,2,4,5,3], you only need to count 1 when mincing 1.
Finally, if there are n numbers of 1? If there are n numbers of 1, the result is 1, and 1 is less than n, then the result is very obvious.
AC Code
class Solution { public: int repeatedNTimes(vector<int>& A) { int assumtp_num = A[0],assumtp_num_Count = 1; int temp_num,Count = 0; for (int i = 1; i < (); ++i) { if(A[i]==assumtp_num) ++assumtp_num_Count; else{ if(A[i]==temp_num) ++Count; else{ if(Count==0){ Count = 1; temp_num = A[i]; } else{ --Count; } } } } //cout<<assumtp_num_Count<<endl; return assumtp_num_Count *2==()?assumtp_num:temp_num; } };
The above is the detailed content of the solution to the Go language LeetCode problem 961 to find the repeating elements in the array of length 2N. For more information about the repetitive elements of the solution to the solution to the length 2N array of Go, please pay attention to my other related articles!