力扣——求众数
給定一個大小為?n?的數(shù)組,找到其中的眾數(shù)。眾數(shù)是指在數(shù)組中出現(xiàn)次數(shù)大于?? n/2 ??的元素。
你可以假設(shè)數(shù)組是非空的,并且給定的數(shù)組總是存在眾數(shù)。
示例?1:
輸入: [3,2,3] 輸出: 3示例?2:
輸入: [2,2,1,1,1,2,2] 輸出: 2class Solution {public int majorityElement(int[] nums) {int count = 1;int maj = nums[0];for (int i = 1; i < nums.length; i++) {if (maj == nums[i])count++;else {count--;if (count == 0) {maj = nums[i + 1];}}}return maj;} }
?
轉(zhuǎn)載于:https://www.cnblogs.com/JAYPARK/p/10732948.html
總結(jié)
- 上一篇: NIO原理及案例使用
- 下一篇: 广度优先搜索(BreadthFirstS