【LeetCode】Majority Numbers

38 篇文章 0 订阅
27 篇文章 0 订阅

【题目】

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.

【分析】

用的是先sort在遍历的方法,O(nlgn).

注意:

1.长度为1的情况

2. 判断符合条件是count>n=max. 是>.没有=,否则会出现{1,1,1,2,2,2,2}返回1的情况。

【代码】我提交的答案

 public int majorityElement(int[] A) {
        int max=A.length/2;
	int count=1;
	Arrays.sort(A);
	if(A.length==1) return A[0];
	for(int i=1;i<A.length;i++){
		if(A[i]==A[i-1])
		{count++;
		if(count>max) return A[i];}
		else count=1;
		}
	 return -1;
    }

【其他参考答案】

1.

Moore's voting algorithm 

O(n) 

sapce: O(1)

不用排序直接遍历一遍,用一个count 进行加减,一旦count =0就换元素。最终,count最多的就是majorty,

int majorityElement(vector<int> &num) {
    int maj;
    int count = 0;
    int n = int(num.size());
    for (int i = 0; i < n; i++){
        if (count == 0){
            maj = num[i];
            count++;
        }
        else if (num[i] == maj){
            count++;
            if (count > n/2) return maj;
        }
        else count--;
    }
    return maj;
}


2. HashMap

 Map<Integer,Integer> result = new HashMap<Integer, Integer>();
            int length = num.length;
            for (int i : num) {
                if (result.containsKey(i)) {
                    result.put(i,result.get(i) + 1);
                } else {
                    result.put(i,1);
                }
                if (result.get(i) >= length / 2 + 1)
                    return i;
            }
            return 0;

3.也是sort的方法,但是很聪明的找到了最多的元素一定出现在中间位置,两行搞定

 public int majorityElement(int[] num) {
    Arrays.sort(num);
    return num[num.length/2];
    }


【答案】来自官网

  1. Runtime: O(n2) — Brute force solution: Check each element if it is the majority element.
  2. Runtime: O(n), Space: O(n) — Hash table: Maintain a hash table of the counts of each element, then find the most common one.
  3. Runtime: O(n log n) — Sorting: Find the longest contiguous identical element in the array after sorting.
  4. Average runtime: O(n), Worst case runtime: Infinity — Randomization: Randomly pick an element and check if it is the majority element. If it is not, do the random pick again until you find the majority element. As the probability to pick the majority element is greater than 1/2, the expected number of attempts is < 2.
  5. Runtime: O(n log n) — Divide and conquer: Divide the array into two halves, then find the majority element A in the first half and the majority element B in the second half. The global majority element must either be A or B. If A == B, then it automatically becomes the global majority element. If not, then both A and B are the candidates for the majority element, and it is suffice to check the count of occurrences for at most two candidates. The runtime complexity, T(n) = T(n/2) + 2n = O(n logn).
  6. Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
    1. If the counter is 0, we set the current candidate to x and the counter to 1.
    2. If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
    After one pass, the current candidate is the majority element. Runtime complexity = O(n).
  7. Runtime: O(n) — Bit manipulation: We would need 32 iterations, each calculating the number of 1's for the ith bit of all n numbers. Since a majority must exist, therefore, either count of 1's > count of 0's or vice versa (but can never be equal). The majority number’s ith bit must be the one bit that has the greater count.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值