961. N-Repeated Element in Size 2N Array

Topic link

961. N-Repeated Element in Size 2N Array

Subject analysis

In array A of length 2N, we have N+1 elements. Exactly one of them is repeated N times. Return this element.

General algorithm problems use mathematical definition methods to describe the problem, so it may be difficult to understand.

Let’s simplify things:

Returns the element in array A that is repeated N times. => Returns the element that occurs N times in array A. Where the number N is half the length of array A.

That makes sense, right?

Train of thought

Input:

  • An array of a.

Need to:

  • Number N: Divide the length of array A by 2.

  • Array_count_values function to count occurrences of elements.

Output:

  • witharray_searchFunctions, fromarray_count_valuesFunction to find the number N.

The final code


      
class Solution {
    function repeatedNTimes($A) {
        $countValues = array_count_values($A);
        $N = count($A)/2;
        returnarray_search($N,$countValues); }}Copy the code

If you find this article useful, you are welcome to subsidize it with love.