leetcode 169- Majority Element
2017-12-13 21:53
423 查看
Given an array of size n, find themajority element. The majority element is the element that appears more than ⌊n/2 ⌋times.
You may assume that the array isnon-empty and the majority element always exist in the array.
题目的意思是有一个数组,数组中有一个数出现的次数大于数组长度的一半,让找出这个数。
方法1:就是对数组进行排序,排序之后的数组的中位数就是目标值。
但是注意冒泡、选择等排序方法都超时了,复杂度O(n2)太高了,所以用sort快排。时间复杂度O(nlogn).
AC代码:
方法2:把每个数出现的次数用一个HashMap记录下来,key是数组中的数,value是该数出现的次数。因为最后想找出现次数最大的数,也就是找最大value对应的key值。时间复杂度O(n).
AC代码:
方法3:可以采用类似于下棋对子的方法。从头开始遍历数组,只要有不一样的两个数就相互对掉,那么最后剩下的那个数就是所求解。这种方法相比于前两种方法很巧妙,最不容易想到。但是时间复杂度O(n),相比于方法一的sort快排O(nlogn)降低了时间复杂度。不利用额外空间,相比于方法二的HashMap降低了空间复杂度。
AC代码:
You may assume that the array isnon-empty and the majority element always exist in the array.
题目的意思是有一个数组,数组中有一个数出现的次数大于数组长度的一半,让找出这个数。
方法1:就是对数组进行排序,排序之后的数组的中位数就是目标值。
但是注意冒泡、选择等排序方法都超时了,复杂度O(n2)太高了,所以用sort快排。时间复杂度O(nlogn).
AC代码:
class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums[nums.size()/2]; } };
方法2:把每个数出现的次数用一个HashMap记录下来,key是数组中的数,value是该数出现的次数。因为最后想找出现次数最大的数,也就是找最大value对应的key值。时间复杂度O(n).
AC代码:
class Solution { public: int majorityElement(vector<int>& nums) { unordered_map<int, int>temp; for(int x:nums) { if (++temp[x]>nums.size()/2) return x; } } };
方法3:可以采用类似于下棋对子的方法。从头开始遍历数组,只要有不一样的两个数就相互对掉,那么最后剩下的那个数就是所求解。这种方法相比于前两种方法很巧妙,最不容易想到。但是时间复杂度O(n),相比于方法一的sort快排O(nlogn)降低了时间复杂度。不利用额外空间,相比于方法二的HashMap降低了空间复杂度。
AC代码:
class Solution { public: int majorityElement(vector<int>& nums) { int count=0,value; for(int x:nums) { if(count==0) { value=x; ++count; } else value==x?++count:--count; } return value; } };
相关文章推荐
- [LeetCode]169. Majority Element(多数元素)
- 【LeetCode】169. Majority Element
- 【LeetCode-169】Majority Element
- ※ Leetcode - Array - 169. Majority Element(快速找出数组中出现过一半以上次数的数,3种写法)
- Leetcode[169]-Majority Element
- [leetcode]#169. Majority Element
- LeetCode 169. Majority Element
- leetcode 169 Majority Element 冰山查询
- LeetCode 169. Majority Element (数组的主要元素、摩尔投票算法)
- Leetcode 169. Majority Element
- LeetCode 169: Majority Element
- LeetCode-169:Majority Element (数组中的多数元素)
- LeetCode Problem 169: Majority Element查找多数元素
- Leetcode-169 Majority Element
- LeetCode:169. Majority Element
- LeetCode 169. Majority Element 解题报告
- leetcode:169 Majority Element-每日编程第十一题
- [LeetCode 169]Majority Element: Moore Voting Algorithm
- [LeetCode]169. Majority Element
- Leetcode#169 Majority Element