-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path169. Majority Element
44 lines (39 loc) · 1.5 KB
/
169. Majority Element
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int len=nums.length;
int result=0;
for(int i=0;i<len/2+1;i++)
if(nums[i]==nums[len/2+i])
{result=nums[i];
break;}
return result;
}
}
/*
There are several things needed to pay attention to.
1.upper index and bottom index
if length is an even number;
for example 6; it needs more than 3 same elements, which is four
the idex of the last element you need to check is 2; which is length/2-1
if length is an odd number;
for example 5;it needs more than 2 same elements, which is 3;
the index of the last element you need to check is 2 ,which is length/2;
Thus if you want to put it together, the index limit should be less than len/2+1;
Further more;
if I write like this;
if(nums[i]==nums[len/2+i])
return nums[i];
it will say missing return statement;
Sometimes if it says illegal start of the type in the return line; basically you misplaced the brace
*/
更简单的做法:
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}
因为如果length是偶数,nums.length/2前面有nums.length/2个元素,就算从0开始都是一样的,也会包括nums.length/2
如果length是奇数,nums.length/2前面和后面有相同的数目的元素,都是(length-1)/2;
所以无论怎样,都会渠道nums.length/2