九章算法系統(tǒng)設(shè)計(jì)SystemDesign2022
? public int majorityElement(int[] nums, int start, int end) {
? ? ? ?if (start == end || start + 1 == end) {
? ? ? ? ? ?return nums[start];
? ? ? ?}
? ? ? ?int mid = (start + end) / 2;
? ? ? ?int left = majorityElement(nums, start, mid - 1);
? ? ? ?int right = majorityElement(nums, mid, end);
? ? ? ?if (left == right) {
? ? ? ? ? ?return left;
? ? ? ?}
? ? ? ?// 左右兩側(cè)數(shù)組中出現(xiàn)次數(shù)最多的數(shù)字不相同
? ? ? ?int leftCount = getCount(nums, start, mid - 1, left);
? ? ? ?int rightCount = getCount(nums, mid, end, right);
? ? ? ?if (leftCount > rightCount) {
? ? ? ? ? ?return left;
? ? ? ?}
? ? ? ?return right;
? ?}
標(biāo)簽: