【leetcode】 Majority_Element
2015-03-01 13:47
260 查看
题目:
解法:
1.先排序,后返回最中间的数:
2.找成对的元素,相同加1,不同减1,最后留下的就是主要的。
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.
解法:
1.先排序,后返回最中间的数:
public int majorityElement1(int[] num) { quickSort(num,0,num.length-1); return num[num.length/2]; } public void quickSort(int[] num,int start,int end){ //递归结束的条件,start>end int pivot = 0; if(start<end){ pivot = fastSort(num,start,end); quickSort(num,start,pivot-1); quickSort(num,pivot+1,end); } } public int fastSort(int[] num,int start,int end){ int temp = 0; while(start<end){ while(start<end&&num[start]<=num[end]) end--; //出循环两种情况,start>end 或者 num[start]>num[end] if(start<end){ temp=num[start]; num[start]=num[end]; num[end]=temp; start++; } while(start<end&&num[start]<=num[end]) start++; if(start<end){ temp=num[start]; num[start]=num[end]; num[end]=temp; end--; } } return start; }
2.找成对的元素,相同加1,不同减1,最后留下的就是主要的。
public int majorityElement(int[] num) { int elem=0; int count=0; for(int i=0;i<num.length;i++){ if(count==0){ elem=num[i]; count++; }else{ if(elem==num[i]) count++; else count--; } } return elem; }
相关文章推荐
- 小白笔记-------------------------------leetcode(169. Majority Element)
- leetcode:Majority Element
- [LeetCode169]Majority Element
- [LeetCode169]Majority Element求一个数组中出现次数大于n/2的数
- leetcode MajorityElement相关问题
- LeetCode Problem 169: Majority Element查找多数元素
- [LeetCode] Majority Element II
- leetcode Majority Element
- 和大神们学习每天一题(leetcode)-Majority Element
- [Leetcode,python] Majority Element 众数
- leetcode-Majority Element
- Leetcode18: Majority Element
- [Leetcode从零开刷]169.Majority Element
- LeetCode Majority Element
- LeetCode--Majority Element(出现次数最多的元素)Python
- leetcode_num169_Majority Element
- 【leetcode】Array—— Majority Element(169)
- 【leetcode】【169】Majority Element
- Divide and Conquer -- Leetcode problem169: Majority Element
- LeetCode---Majority Element