原文链接:https://leetcode-cn.com/problems/majority-element/
题目:
思路分析:这道题是让我们找出给定数组当中的多数元素,最简单的方法就是我们先对数组进行排序,然后再进行操作。
1.借用Arrays.sort()方法对数组进行排序。
2.因为是排过序的,所以只用看数组前面一半的元素,后面就不用看了。
3.遍历数组元素进行操作即可。
更简单的方法就是排完序之后直接返回数组当中最中间角标的元素就行,因为我们是排完序的,你细细品!
源代码:
class Solution {
public int majorityElement(int[] nums){
Arrays.sort(nums);
return nums[nums.length / 2];
/*
int n = 0;
int ncount = 0;
for(int i = 0;i < nums.length;){
if(i > nums.length / 2){
break;
}
int count = 1;
for(int j = i + 1;j < nums.length;j++){
if(nums[j] == nums[i]){
count++;
}else{
break;
}
}
if(count>ncount){
ncount = count;
n = nums[i];
}
i+=count;
}
return n;
*/
}
}