主元素算法

counting 大于 n/2, n/3都可以用投票法来做

int count = 1 ;
        int major = nums[0];
        for(int i = 1, size = nums.size(); i < size; i++) {
            if (count == 0) {
                major = nums[i];
                count = 1;
            }
            else {
                if (nums[i] == major)
                    count++;
                else {
                    count--;
                }
            }
        }
        return major;
 int cnt1 = 0;
        int cnt2 = 0;
        int a = 0;
        int b = 1;
        for (auto val : nums) {
            if (val == a) {
                cnt1++;
            }
            else if (val == b) {
                cnt2++;
            }
            else if (cnt1 == 0) {
                a = val;
                cnt1 = 1;
            }
            else if (cnt2 == 0) {
                b = val;
                cnt2 = 1;
            }
            else {
                cnt1--;
                cnt2--;
            }
        }

你可能感兴趣的:(主元素算法)