Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
题解:设置两个变量,一个是current,初始化为A[0];另一个是count,记录current这个元素当前为止出现的次数。然后遍历A,如果当前元素和current相等,则count加1;否则,看count是否为0,如果count已经为0,就直接把current赋值成当前元素;如果count不为0,就把count减一即可。
这个思路的根本就是找不相等的元素配对,如果有两个不相等的元素,就把他们两个抵消,那么最后没有抵消掉的那个元素,就是出现次数超过⌊ n/2 ⌋的。
JAVA版本代码:
1 public class Solution { 2 public int majorityElement(int[] num) { 3 int current = num[0]; 4 int count = 0; 5 for(int i = 1;i < num.length;i++){ 6 if(current == num[i]) 7 count++; 8 else{ 9 if(count >0){ 10 count--; 11 }else { 12 current = num[i]; 13 } 14 } 15 } 16 return current; 17 } 18 }
时间: 2024-11-05 16:25:06