Pointing to Offer - Interview Question 29: Numbers that appear more than half the times in the array

Numbers that appear more than half the times in an array


Question: There is a number in an array that appears more than half the length of the array, please find the number. For example enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears in the array 5 times, which is more than half the length of the array, 2 is output. Output 0 if not present.

Input: {1,2,3,2,2,2,5,4,2}

output: 2

Ideas: 1. According to the characteristics of this question, the time complexity is O(n) and the space complexity is O(1) with one traversal.
2. Because the number of occurrences of a number in the array exceeds half of the length of the array
3. That is, the number appears at least n/2 + 1 times, in other words, the number of occurrences of the number is more than the number of occurrences of all other remaining numbers.
4. Using this feature, when we traverse from the beginning, we put the first number. a[0], create 2 variables: one is a number, the other is the number of times the number appears, initialized to 1;
5. If a[1] is the same as a[0], set it to add 1 (ie 2) , if a[1] is different from a[0], subtract 1, if the number of occurrences of the number is already 0, then replace the number with the latter one, and reassign the number to 1.

/*
题目:数组中出现次数超过一半的数字
*/

#include<iostream>
#include<vector>
using namespace std;

bool checkArray(vector<int> number, int num){
    int time = 0;
    for (int i = 0; i < number.size(); i++){
        if (number[i] == num){
            time++;
        }
    }
    if (time * 2>number.size()){
        return true;
    }
    else{
        return false;
    }
}

int findNumber(vector<int> number){
    //num表示某个数字,numTime表示某个数字出现的时间
    int num;
    int numTime;
    num = number[0];
    numTime = 1;
    for (int i = 1; i < number.size(); i++){
        if (numTime == 0){
            num = number[i];
            numTime++;
        }
        else if (num == number[i]){
            numTime++;
        }
        else{
            numTime--;
        }
    }
    //这里判断输入的数组是否符合要求,即输入的数组中,是否存在某个元素出现的次数超过数组的长度的一半
    if (checkArray(number, num)){
        return num;
    }
    return 0;
}

int main(){
    vector<int> number;
    int temp;
    //出现的次数
    int occurrenceNumber;
    do{
        cin >> temp;
        number.push_back(temp);

    } while (cin.get() != '\n');
    occurrenceNumber = findNumber(number);
    cout << occurrenceNumber;
    system("pause");
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325512009&siteId=291194637