给出一个数组,找出其中过半的元素。
思路:
因为这里的假设是一定存在过半的元素。
用Moore Voting法,需要 O(n) 的时间和 O(1) 的空间。
先假设count =1 , majority是第一个元素,从左到右遍历数组,当前数字 != majority时,count–。
直到count== 0 时, 更新mojority为当前数字,count重新置为1。如果当前数字==majority,那么count++
因为题目中假设一定存在这样的元素,所以最后不需要再验证majority的个数是否>n/2
public int majorityElement(int[] nums) {
int n = nums.length;
int count = 1;
int result = nums[0];
for(int i = 1; i < n; i++) {
if(nums[i] == result) {
count ++;
} else {
count --;
if(count == 0) {
result = nums[i];
count = 1;
}
}
}
return result;
}
如果没说一定存在,最后需要加上验证
public int majorityElement(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int count = 1;
int n = nums.length;
int major = nums[0];
for(int i = 1; i < n; i++) {
if(nums[i] == major) {
count ++;
} else {
count --;
if(count == 0) {
major = nums[i];
count = 1;
}
}
}
count = 0;
for(int i = 0; i < n; i++) {
if(nums[i] == major) {
count ++;
}
}
if(count > n/2) {
return major;
}
return 0;
}