[LeetCode] 1287. Elements that appear more than 25% in an ordered array (C++)

1 topic description

Give you a non-decreasing ordered array of integers. It is known that there is exactly one integer in this array, and its number of occurrences exceeds 25% of the total number of elements in the array.
Please find and return this integer

2 Example description

Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6

3 Problem solving tips

1 <= arr.length <= 10^4
0 <= arr[i] <= 10^5

4 Problem-solving ideas

The official way to conclude the question: Since the array arr is already in order, the same number appears in a continuous position in arr. So we can traverse the array once and count the number of occurrences of each number. As long as it is found that the number of occurrences of a certain number exceeds 25% of the length of the array arr, then this number is the answer.

5 Detailed source code (C++)

class Solution {
    
    
public:
    int findSpecialInteger(vector<int>& arr) {
    
    
        int res = arr[0] , count = 0 ;
        for ( int i = 0 ; i < arr.size() ; i ++ )
        {
    
    
            if ( arr[i] == res )
            {
    
    
                count ++ ;
                if ( count > arr.size() / 4 )
                {
    
    
                    return res ;
                }
            }
            else
            {
    
    
                res = arr[i] ;
                count = 1 ;
            }
        }
        return -1 ;
    }
};

Guess you like

Origin blog.csdn.net/Gyangxixi/article/details/114459293