1. 程式人生 > >劍指offer 28 陣列中出現次數超過一半的數字

劍指offer 28 陣列中出現次數超過一半的數字

1 先排序 ,再遍歷,計數值大於一半,則為那個數

2 陣地攻守 ,計數相同加1,不同減1,計數為0,換接下來一個數,計數為1

 

//陣列中出現次數超過一半的數字
    int MoreHalfNumber(vector<int> &numbers) {
        if (numbers.size() == 0) {
            return 0;
        }
        else if (numbers.size() == 1) {
            return numbers[0];
        }

        sort(numbers);

        int res = 0;
        int count = 0;
        for (int i = 0; i < numbers.size(); i++) {
            if (numbers[i] == numbers[i+1]){
                count++;//與後面一個數相等,次數加1
            }//執行完後,,跳到if
            else {
                //此時,numbers[i]!=numbers[i+1]了
                cout << numbers[i] << "occus=cishu=" << count << endl;
                count = 1;//重置count=1
            }
            if (count > numbers.size()/2) {
                res = numbers[i];
                break;//某個數次數超過一半,跳出迴圈
            }
            //特殊處理,為什麼不是i==numbers.size() - 1,
            //已經與後面一個數不等了,count置1
            if (i == numbers.size() - 2) {
                cout <<  numbers[i+1] << "occus=" << count << endl;
            }

        }
        return res;//返回次數超過一半的那個值
    }
    void sort(vector<int> &array) {
        for (int i = 0; i < array.size(); i++) {
            for(int j = i-1; j >= 0; j--) {
                if (array[j] > array[j+1]) {//後邊的數小於前邊就交換
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                }
            }
        }


    }

    //陣地攻守,數字相同,加1,數字不同減1
    int MoreHalfNumber2(vector<int> numbers) {
        if (numbers.size() == 0) {
            return 0;
        }
        else if (numbers.size() == 1) {
            return numbers[0];
        }
        int count = 1;
        int num = numbers[0];
        for (int i = 1;i < numbers.size();i++) {
            if (numbers[i] == num) {//計數+1
                count++;
            }
            else {
                count--;//不同,-1
            }
            if (count== 0) {
                num = numbers[i];//重置num
                count=1;
            }


        }

        cout << "find" <<  num  << endl;
        //驗證是不是這個數
        int counts = 0;
        for (int i = 0; i < numbers.size(); i++) {
            if(numbers[i] == num) {
                counts++;
            }
        }
        //次數超過一半
        if (counts > numbers.size()/2) {
            cout << "number=" << num << endl;
            return num;
        }
        else {
            return 0;
        }
    }