[Leetcode]-Majority Element
来源:互联网 发布:mac系统怎么看bilibili 编辑:程序博客网 时间:2024/05/16 13:24
题目:Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
找出数组中出现超过⌊ n/2 ⌋次的数据
三种解法:
1、参考别人的,很巧的解法
2、插入排序,排序后,nums⌊ n/2 ⌋必定是出现超过⌊ n/2 ⌋次的数据,而且插入排序在数据接近排序好的顺序的时候,时间复杂度为O(n)
3、快排,和2一样,只不过速度稍快 12ms
You may assume that the array is non-empty and the majority element always exist in the array.
typedef int elementtype;//infact CUT = 10 is the best solution#define CUT 10 void swap(int *a,int *b) { int tem = *a; *a = *b; *b = tem; } void insertion(elementtype A[],int n) { int p = 0 ; int j = 0 ; for(p=1;p<n;p++ ) { elementtype tem = A[p] ; for(j=p;j>0&&A[j-1]>tem;j--) { A[j] = A[j-1]; } A[j] = tem; } } elementtype median3(elementtype A[],int left ,int right) { int center = (left +right) / 2; if(A[left]>A[center]) swap(&A[left],&A[center]); if(A[left]>A[right]) swap(&A[left],&A[right]); if(A[center]>A[right]) swap(&A[center],&A[right]); swap(&A[center],&A[right-1]); return A[right-1]; } void Qsort(elementtype A[],int left, int right) { int i,j; elementtype pivot; if(left + CUT<= right) { pivot = median3(A,left,right); //select middle element as pivot i = left;j = right-1; for(;;) { while(A[++i]<pivot){} while(A[--j]>pivot){} if(i<j) swap(&A[i],&A[j]); else break; } swap(&A[i],&A[right-1]); Qsort(A,left,i-1); Qsort(A,i+1,right); } else insertion(A+left,right-left+1); } int majorityElement(int* nums, int numsSize) { //solution 1 :13ms /* int cnt = 0, res; for (int i = 0; i < numsSize; ++i) { if (cnt == 0) res = nums[i]; if (res == nums[i]) ++cnt; else --cnt; } return res; */ //solution 2 insertion sort :28ms /* int p = 0 ; int j = 0 ; for(p=1;p<numsSize;p++ ) { int tem = nums[p] ; for(j=p;j>0&&nums[j-1]>tem;j--) { nums[j] = nums[j-1]; } nums[j] = tem; } return nums[numsSize/2]; */ //solution 3 qiuk sort :12ms Qsort(nums,0,numsSize-1); return nums[numsSize/2];}
1 0
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- [leetcode]Majority Element
- [LeetCode]Majority Element
- Leetcode: Majority Element
- DEVICE_ATTR实例分析
- Java对文本进行分词
- CAS实现SSO(单点登录)原理
- matlab画棋盘格程序
- LayoutTransition 使用
- [Leetcode]-Majority Element
- >Input_dev结构体-事件支持
- 玩转oracle学习第五天
- How to use CyclicBarrier in Java - Concurrency Tutorail(转)
- 莫名其妙的Parse error: syntax error, unexpected $end 分类: php相关 2008-12-17 20:25 7086人阅读 评论(3) 收藏 举报 phpg
- [每日刷题(2015/6/27)]在一个分布式银行系统中,你如何测试一台ATM机?
- >输入子系统层次结构
- 文章标题
- [STL]C++中placement new操作符(经典)