剑指 offer 39 数组中出现次数超过一半的数字
排序的方法
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
时间复杂度是
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn),因为排序最好的时间复杂度是
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn)。
基于partion函数的时间复杂度为 O ( n ) O(n) O(n)的算法
class Solution {
public int majorityElement(int[] nums) {
int len = nums.length;
int l=0;
int r = len-1;
int mid = partion(nums,l,r);
while (mid != len/2){
if(mid<len/2){
l=mid+1;
}else{
r = mid-1;
}
mid = partion(nums,l,r);
}
return nums[mid] ;
}
public int partion(int[] nums, int l,int r){
// int rand =l+(int)(Math.random()*(r-l+1));
// swap(nums,rand,r);
int small = l-1;
for(int i=l;i<r;i++){
if(nums[i]<=nums[r]){
small++;
if(small!=i){
swap(nums,small,i);
}
}
}
small++;//small 之前的都是小于等于 nums[r]
swap(nums,small,r);//现在的 small 是等于 nums[r]
return small;
}
public void swap(int[] nums,int i,int j){
if(i==j){
return;
}
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
摩尔投票法
太魔幻了!!!
参考
数组中有一个数字出现的次数超过数组长度的一半,也就是说它出现的次数比其他所有数字出现的次数之和还要多。因此,可以考虑在遍历数组的时候保存两个值:一个是数组中的一个数字;另一个是次数。当遍历到下一个数字的时候如果下一个数字和之前保存的数字相同,则次数加 1;如果下一个数字和之前保存的数字不同,则次数减一。如果次数为 0,那么需要保存下一个数字,并把次数设为 1。由于要找的数字出现的次数比其他所有数字出现的次数之和还要多,那么要找的数字肯定是最后一次把次数设为 1 时对应的数字。
摩尔投票法的基本思想是:在每一轮投票过程中,从数组中删除两个不同的元素,直到投票过程无法继续,此时数组为空或者数组中剩下的元素都相等。
- 如果数组为空,则数组中不存在主要元素;
- 如果数组中剩下的元素都相等,则数组中剩下的元素可能为主要元素。
class Solution {
public int majorityElement(int[] nums) {
int votes = 0;
int x=nums[0];
int len = nums.length;
for(int i=0;i<len;i++){
if(votes==0){
x = nums[i];
}
if(nums[i] == x){
votes++;
}else{
votes--;
}
}
return x;
}
}
时间复杂度
O
(
n
)
O(n)
O(n)。
空间复杂度
O
(
1
)
O(1)
O(1)。
哈希表统计法
class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
int res = nums[0];
int cishu =1;
int len = nums.length;
for(int i=0;i<len;i++){
if(map.containsKey(nums[i])){
map.replace(nums[i],map.get(nums[i])+1);
if(cishu<map.get(nums[i])){
res = nums[i];
cishu = map.get(nums[i]);
}
}else{
map.put(nums[i],1);
}
}
return res;
}
}
时间复杂度
O
(
n
)
O(n)
O(n)。
空间复杂度
O
(
n
)
O(n)
O(n)。