数组中出现次数超过一半的数字-39
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
假设数组非空,并且一定存在满足条件的数字。
思考题:
- 假设要求只能使用 O(n) 的时间和额外 O(1) 的空间,该怎么做呢?
样例
输入:[1,2,1,1,3]
输出:1
思路:
partition思想
class Solution {
public int moreThanHalfNum_Solution(int[] nums) {
int left = 0, right = nums.length - 1;
int mid = left + (right - left) / 2;
int index = partition(nums, left, right);
while(index != mid){
if(index > mid) index = partition(nums, left, index - 1);
else if(index < mid) index = partition(nums, index + 1, right);
}
return nums[index];
}
private int partition(int[] nums, int left, int right){
int temp = nums[left];
while(left < right){
while(left < right && nums[right] >= temp) right--;
nums[left] = nums[right];
while(left < right && nums[left] <= temp) left++;
nums[right] = nums[left];
}
nums[left] = temp;
return left;
}
}
时间复杂度 O(n),空间复杂度 O(1) 的做法
class Solution {
public int moreThanHalfNum_Solution(int[] nums) {
int res = 0, count = 0;
for(int i = 0; i < nums.length; i++){
if(count == 0){
res = nums[i];
count = 1;
}
else if(res != nums[i]) count--;
else count++;
}
return res;
}
}