forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
30 lines (29 loc) · 823 Bytes
/
Solution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {
public int MajorityElement(int[] nums) {
return Sort(nums, 0, nums.Length - 1);
}
private int Sort(int[] nums, int left, int right)
{
if (left == right) return nums[left];
var targetIndex = nums.Length / 2;
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;
}
}
if (targetIndex <= j) return Sort(nums, left, j);
if (targetIndex >= i) return Sort(nums, i, right);
return mid;
}
}