class Solution {
public:
int majorityElement(vector<int>& nums) {
int first = 0;
int end = nums.size()-1;
int index = (first+end)/2;
int p = partition(nums,first,end);
while(p!=index)
{
if (p<index)
{
first = p+1;
p = partition(nums,first,end);
}
if (p>index)
{
end = p-1;
p = partition(nums,first,end);
}
}
return nums[p];
}
int partition(vector<int> &nums, int first, int end)
{
int key = nums[first];
int keypos = first;
if (first<end)
{
while(first<end)
{
while((first<end)&&nums[end]>key)
end--;
if (first<end)
{
nums[keypos] = nums[end] ;
first++;
keypos = end;
}
while((first<end)&&nums[first]<key)
first++;
if (first<end)
{
nums[keypos] = nums[first] ;
end--;
keypos = first;
}
}
nums[first] = key;
return first;
}
}
};
public:
int majorityElement(vector<int>& nums) {
int first = 0;
int end = nums.size()-1;
int index = (first+end)/2;
int p = partition(nums,first,end);
while(p!=index)
{
if (p<index)
{
first = p+1;
p = partition(nums,first,end);
}
if (p>index)
{
end = p-1;
p = partition(nums,first,end);
}
}
return nums[p];
}
int partition(vector<int> &nums, int first, int end)
{
int key = nums[first];
int keypos = first;
if (first<end)
{
while(first<end)
{
while((first<end)&&nums[end]>key)
end--;
if (first<end)
{
nums[keypos] = nums[end] ;
first++;
keypos = end;
}
while((first<end)&&nums[first]<key)
first++;
if (first<end)
{
nums[keypos] = nums[first] ;
end--;
keypos = first;
}
}
nums[first] = key;
return first;
}
}
};