LeetCode Majority Element

来源:互联网 发布:java代码调用ant出错 编辑:程序博客网 时间:2024/06/04 19:40

题目:

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.

题意:

就是给你一个Array,然后求其中最大的元素。所谓最大的元素也就是指其中出现次数大于 ⌊ n/2 ⌋的数。


参考《编程之美》,发现有一种非常简单的方法可以来实现这个过程,那就是先不用排序,每一个删除两个不同的ID,在剩下的ID中,出现次数多于

⌊ n/2 ⌋的数必然还是会超过总数的一半,所以我们可以考虑将这个问题以大化小,然后逐层降低总数,使得这个时间复杂度降为O(n),就行了

public int majorityElement(int[] nums){int length = nums.length;int candidate = 0;int nTimes,i;for(i = nTimes = 0; i < length; i++){if(nTimes == 0){candidate = nums[i];nTimes = 1;}else{if(candidate == nums[i])nTimes ++;elsenTimes --;}}return candidate;}


0 0
原创粉丝点击