我的答案
class Solution {public int majorityElement(int[] nums) {int len = nums.length;Arrays.sort(nums);int count = 1;int res = 0;if(len == 1){return nums[0];}for(int i=0; i<len-1; i++){if(nums[i]==nums[i+1]){count++;}else{count = 1;}if(count>len/2){res = nums[i];break;}}return res;}
}
超级震惊的答案
学习思想
class Solution {public int majorityElement(int[] nums) {Arrays.sort(nums);return nums[nums.length / 2];}
}作者:力扣官方题解
链接:https://leetcode.cn/problems/majority-element/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
哈希表
哈希表是不是用C++代码更方便一点啊???
class Solution {
public:int majorityElement(vector<int>& nums) {unordered_map<int, int> counts;int majority = 0, cnt = 0;for (int num: nums) {++counts[num];if (counts[num] > cnt) {majority = num;cnt = counts[num];}}return majority;}
};作者:力扣官方题解
链接:https://leetcode.cn/problems/majority-element/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。