1 Star 0 Fork 0

agony/LeetCode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
229.MajorityElementII.cs 1.61 KB
一键复制 编辑 原始数据 按行查看 历史
Kai Yang 提交于 2015-07-26 16:31 . 229. Majority Element II
using System.Collections.Generic;
using System.Linq;
public class Solution {
public IList<int> MajorityElement(int[] nums) {
if (nums.Length == 0) return new int[0];
var targetIndices = new [] { nums.Length / 3, nums.Length - nums.Length / 3 - 1 }.Distinct().ToList();
var candidates = Sort(nums, 0, nums.Length - 1, targetIndices).Distinct();
return candidates.Where(c => nums.Count(n => n == c) > nums.Length / 3).ToList();
}
private IList<int> Sort(int[] nums, int left, int right, IList<int> targetIndices)
{
if (left == right) return new [] { nums[left] };
var mid = nums[(left + right) / 2];
var i = left;
var j = right;
while (i <= j)
{
while (nums[i] < mid) ++i;
while (nums[j] > mid) --j;
if (i <= j)
{
var temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
++i;
--j;
}
}
var result = new List<int>();
var leftTargetIndices = new List<int>();
var rightTargetIndecies = new List<int>();
foreach (var targetIndex in targetIndices)
{
if (targetIndex <= j) leftTargetIndices.Add(targetIndex);
else if (targetIndex >= i) rightTargetIndecies.Add(targetIndex);
else result.Add(mid);
}
if (leftTargetIndices.Count > 0) result.AddRange(Sort(nums, left, j, leftTargetIndices));
if (rightTargetIndecies.Count > 0) result.AddRange(Sort(nums, i, right, rightTargetIndecies));
return result;
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/agony2020/LeetCode.git
git@gitee.com:agony2020/LeetCode.git
agony2020
LeetCode
LeetCode
master

搜索帮助