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.
开始采用的比较笨的办法,就是遍历数组,从第一个开始,计算这个值出现的所有次数,再计算第二个值出现的次数,取两个之中较大的一个数:
在idea跑了一下好像都可以通过,但是提交答案的时候好像超时了。。。。算法如下:
public class Solution {
public int majorityElement(int[] nums) {
int numtemp = 0;
if(nums.length == 1){
return nums[0];
}
for(int i = 0; i <nums.length-1; i++){
int temp1 = nums[i];
int num1 = 0;
int temp2 = nums[i+1];
int num2 = 0;
for(int j =0; j < nums.length;j++){
if(temp1 == nums[j]){
num1++;
}
}
for(int j =0; j < nums.length;j++){
if(temp2 == nums[j]){
num2++;
}
}
numtemp = num1 > num2 ? temp1 : temp2;
}
return numtemp;
}
}
后来仔细一想这个题目,这不是脑筋急转弯吗???这个数出现的次数超过数组总长度的一半,那么,我把这个数组直接排序一下,取他的中间值不就是我们要的那个数字了么。尼玛!!!两句话搞定!!!
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}