【10_169】Majority Element
今天遇到的题都挺难的,不容易有会做的。
下面是代码,等明天看看Discuss里面有没有简单的方法~
Majority Element
My SubmissionsTotal Accepted: 79833 Total Submissions: 208075 Difficulty: Easy
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Java写法,遇到一个数字就标记一次,最后看谁的标记数目大于 ⌊ n/2 ⌋
1 public class Solution { 2 public int majorityElement(int[] nums) { 3 int n = nums.length; 4 int[][] count = new int[n][2]; 5 for (int i = 0; i < n; i++) { 6 count[i][1] = 0; 7 } 8 9 count[0][0] = nums[0]; 10 count[0][1] = 1; 11 int ss = 1; 12 for (int i = 1; i < n; i++) { 13 for (int j = 0; j < ss; j++) { 14 if(count[j][0] == nums[i]) { 15 count[j][1]++; 16 } 17 else if (j == ss - 1) { 18 count[ss][0] = nums[i]; 19 ss++; 20 } 21 } 22 } 23 int pan; 24 if(n % 2 == 0) 25 pan = n / 2; 26 else 27 pan = (n - 1) / 2; 28 for (int i = 0; i < n; i++) { 29 if(count[i][1] > pan) 30 return count[i][0]; 31 } 32 33 return 0; 34 } 35 }