数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
假设数组非空,并且一定存在满足条件的数字。
思考题:
假设要求只能使用 O(n) 的时间和额外 O(1) 的空间,该怎么做呢?
样例
输入:[1,2,1,1,3]
输出:1
数学
时间复杂度O(n)
class Solution {
public int moreThanHalfNum_Solution(int[] nums) {
int val = nums[0];
int count = 1;
for(int i = 1; i < nums.length;i++){
if(val == nums[i]){
count++;
}else{
if(count == 1){
val = nums[i];
}else{
count--;
}
}
}
return val;
}
}
2333
时间复杂度O(nlogn)
class Solution {
public int moreThanHalfNum_Solution(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
Arrays.sort(nums);
return nums[nums.length/2];
}
}