多數元素
- 關於摩爾投票法:
候選人(cand_num)
初始化爲nums[0]
,票數count
初始化爲1
。
當遇到與cand_num
相同的數,則票數count = count + 1
,否則票數count = count - 1
。
當票數count
爲0
時,更換候選人,並將票數count
重置爲1
。
遍歷完數組後,cand_num
即爲最終答案。
- 爲何這行得通呢?
投票法是遇到相同的則票數 + 1,遇到不同的則票數 - 1。
且“多數元素”的個數> ⌊ n/2 ⌋,其餘元素的個數總和<= ⌊ n/2 ⌋。
因此“多數元素”的個數 - 其餘元素的個數總和 的結果 肯定 >= 1。
這就相當於每個“多數元素”和其他元素 兩兩相互抵消,抵消到最後肯定還剩餘至少1個“多數元素”。
所以無論數組是1 2 1 2 1,亦或是1 2 2 1 1,總能得到正確的候選人。
public class Main {
public int majorityElement(int[] nums) {
int cand_num = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (cand_num == nums[i]) {
count++;
} else {
if (--count == 0) {
cand_num = nums[i];
count = 1;
}
}
}
return cand_num;
}
}
求衆數II
大於1/3意味着最多可能有兩個候選人,所以我們就假設爲兩個候選人進行投票
初始化從第0個人開始,沒人0票
如果遇到候選人,票數+1
如果沒有遇到候選人且候選人票數爲0,更換候選人
如果沒有遇到候選人且候選人票數不爲0,所有候選人票數-1
然後再統計兩個候選人的票數
如果大於1/3就當選
題解參考
關於摩爾投票的動畫可以去題解看
public class Main {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
//定義兩個候選人的票數
int cand1 = 0, cand2 = 0;
int count1 = 0, count2 = 0;
//開始投票
for (int num : nums) {
//如果是候選人1
if (num == cand1) {
count1++;
continue;
}
//如果是候選人1
if (num == cand2) {
count2++;
continue;
}
//如果不是cand1也不是cand2,判斷有沒有候選人還沒有票,沒有就換人
if (count1 == 0) {
cand1 = num;
count1++;
continue;
}
if (count2 == 0) {
cand2 = num;
count2++;
continue;
}
//如果兩個候選人都還有票,就都-1
count1--;
count2--;
}
//驗證票數是否滿足大於1/3
count1 = 0;
count2 = 0;
for (int num : nums) {
if (cand1 == num) count1++;
else if (cand2 == num) count2++;
}
if (count1 > nums.length / 3) res.add(cand1);
if (count2 > nums.length / 3) res.add(cand2);
return res;
}
}