java 找出n个元素数组中重复次数最多的数(假设出现次数大于n/2)

题目:

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.

此道题有多种解法,可以直接排序然后取数组中间元素。但此算法最大复杂度为O(n^2),此处我们采取数组中两个元素两两抵消的方式,则剩下的一定是重复次数最多的元素。算法如下:

public class Solution {
    public int majorityElement(int[] nums) {
        int count = 0;
        int temp =0;
        for(int i=0;iif(count==0){
                temp = nums[i];
                count++;
            }else{
                if(temp==nums[i])
                    count++;
                else
                    count--;
            }
        }
        return temp;
    }
}

你可能感兴趣的:(leetcode)