1、来源:点击打开链接
2、题目:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
3、暴力破解,又超时,宝宝 心里苦啊int majorityElement(int* nums, int numsSize) {
int i,j,f,k=0;
int *a=(int*)malloc(sizeof(int)*numsSize);
for(i=0;i<numsSize;i++)
a[i]=0;
for(i=0;i<numsSize;i++){
if(i==0){
a[0]++;
}
else{
f=0;
for(j=0;j<i;j++){
if(nums[j]==nums[i]){
f=1;
break;
}
}
if(f==0){
a[i]++;
}
else
a[j]++;
}
}
for(i=0;i<numsSize;i++){
if(a[i]>numsSize/2){
break;
}
}
return nums[i];
}
4、参考:
点击打开链接
int majorityElement(int* nums, int numsSize) {
int i,count=1,major=nums[0];
for(i=1;i<numsSize;i++){
if(count==0){
count++;
major=nums[i];
}
else if(major==nums[i]) count++;
else count--;
}
printf("%d\n",major);
return major;
}
Great idea!
And I want to express my thinking of this solution.
When count != 0 , it means nums[1...i] has a majority,which is major in the solution.
When count == 0 , it means nums[1...i ] doesn't have a majority, so nums[1...i ] will not help nums[1...n].And then we have a subproblem of nums[i+1...n].
I think it's kind of DP.
5、另一种思路,排序之后中间那个元素就是出现最多的