LeetCode -- Majority Element II
題目描述:
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
本題就是需要計算一個數組中出現次數超過n/3次的元素。
暫時沒想出如何使用O(1)的空間復雜度來做,思路還是使用哈希來完成。
實現代碼:
public class Solution {
public IList MajorityElement(int[] nums)
{
if(nums == null || nums.Length == 0){
return new List();
}
var hash = new Dictionary();
var len = nums.Length;
for (var i = 0;i < len; i++)
{
if(!hash.ContainsKey(nums[i]))
{
hash.Add(nums[i],1);
}
else{
hash[nums[i]]++;
}
}
var ret = new List();
foreach(var k in hash.Keys)
{
if(hash[k] > len / 3){
ret.Add(k);
}
}
return ret;
}
}