-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
43 lines (32 loc) · 1.13 KB
/
Solution.java
File metadata and controls
43 lines (32 loc) · 1.13 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Solution {
public int majorityElement(int[] nums) {
int low = 0;
int high = nums.length - 1;
while (true) {
int index = partition(nums, low, high);
if (index == nums.length / 2)
return nums[index];
else if (index > nums.length / 2)
high = index - 1;
else
low = index + 1;
}
}
private int partition(int[] nums, int low, int high) {
int pivotIdx = (int)(Math.random() * (high - low + 1)) + low;
int pivot = nums[pivotIdx];
nums[pivotIdx] = nums[low];
int lowIdx = low;
int highIdx = high;
while (lowIdx < highIdx) {
while (lowIdx < highIdx && nums[highIdx] >= pivot)
highIdx--;
nums[lowIdx] = nums[highIdx];
while (lowIdx < highIdx && nums[lowIdx] <= pivot)
lowIdx++;
nums[highIdx] = nums[lowIdx];
}
nums[lowIdx] = pivot;
return lowIdx;
}
}