Lc169_多數元素
阿新 • • 發佈:2020-07-15
//給定一個大小為 n 的陣列,找到其中的多數元素。多數元素是指在陣列中出現次數大於 ⌊ n/2 ⌋ 的元素。 // // 你可以假設陣列是非空的,並且給定的陣列總是存在多數元素。 // // // // 示例 1: // // 輸入: [3,2,3] //輸出: 3 // // 示例 2: // // 輸入: [2,2,1,1,1,2,2] //輸出: 2 // // Related Topics 位運算 陣列 分治演算法 package leetcode.editor.cn; //Java:多數元素 public class P169MajorityElement{ public static void main(String[] args) { Solution solution = new P169MajorityElement().new Solution(); // TO TEST } //leetcode submit region begin(Prohibit modification and deletion) class Solution { //摩爾斯投票法 public int majorityElement(int[] nums) { int count= 1; int represent = nums[0]; for (int i = 1; i < nums.length; i++) { if(represent == nums[i]){ count++; }else{ count--; if(count==0){ represent = nums[i]; count=1; } } } return represent; } } //leetcode submit region end(Prohibit modification and deletion) }