topic:
The number of occurrences of a number in the array exceeds half of the length of the array. Please find out this number.
You can assume that the array is non-empty, and there will always be a majority of elements in a given array.
Example 1:
Input: [1, 2, 3, 2, 2, 2, 5, 4, 2]
Output: 2
Analysis: Because a number exceeds half the length of the array, this number must exist in the middle of the array.
Note: Prevent the array subscript from crossing the boundary. If the number of the array is an odd number 9, there is int[] i1=new int{1,1,1,1,1,2,3,4,5}, then i1[4] is returned, and there is int[] i2={ 1,2,3,4,5,5,5,5,5}, then i1[4] is returned. Needless to say the even number...
Problem solving:
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[(nums.length/2)];//注意nums.length/2和nums.length/2+1的问题,后者数组下标越界
}
}