More than 25% of the number of elements in the array 1287. orderly appearance

Problem-solving ideas:

1.cnt recording element appears the same number, the initial value 1, times = (int) arr.length * 0.25;

2 through the array, if the current element and the previous element are equal, then add 1 cnt

3. If the current element and the previous element do not equal, 1 is set to cnt

4. If cnt> times, this element is found, return directly to

Time complexity of O (n)

Space complexity O (1)

Code:

class Solution {
    public int findSpecialInteger(int[] arr) {
        int len=arr.length;
        int times=(int)(len*0.25);
        int cnt=1;
        for(int i=1;i<len;++i){
            if(arr[i-1]==arr[i]){
                cnt++;
            }
            else{
                cnt=1;
            }
            if(cnt>times){
                return arr[i];
            }
        }
        return arr[0];
    }
}

 

Published 158 original articles · won praise 13 · views 20000 +

Guess you like

Origin blog.csdn.net/junjunjiao0911/article/details/104101870