169. Majority Element
来源:互联网 发布:淘宝荣耀旗舰店可靠吗 编辑:程序博客网 时间:2024/06/05 00:33
**问题描述:
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,1,3,1,4,5]对应的辅助数组应存放的是[1,2,1,3,1,1]
下面附代码,欢迎大牛们指点:
public class Solution { public int majorityElement(int[] nums) { int n = nums.length; int[] another = new int[n]; for(int i=0;i<n;i++){ boolean flag = false; for(int j=i-1;j>=0;j--){ if(nums[i]==nums[j]){ another[i]=another[j]+1; flag=true; break; } } if(flag==false){ another[i]=1; } //在这里判断,可以减少运行时间 if(another[i]>n/2){ return nums[i]; } } int max=0; for(int i=0;i<another.length;i++){ if(another[max]<another[i]){ max = i; } } return nums[max]; }}
0 0
- 169.Majority Element && 229. Majority Element II
- [LeetCode]169.Majority Element
- LeetCode 169.Majority Element
- 【LeetCode】169.Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- 169.Majority Element
- [leetcode] 169.Majority Element
- 169. Majority Element
- Leetcode 169. Majority Element
- 【LeetCode】169. Majority Element
- [LeetCode]169. Majority Element
- 169. Majority Element LeetCode
- 169. Majority Element
- 169. Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- Leetcode 169. Majority Element
- eclipse的pydev支持
- 自动适配 使用masonry 第三方
- spring常用注解
- AppPay
- B. Finding Team Member
- 169. Majority Element
- 遍历List时 删除元素
- MySQL 1045 登录失败
- [Java语言] Java网络请求工具类
- LeetCode 26, 80, 81, 82, . Remove Duplicates from Sorted Array/ List i, ii
- 3款搜索引擎试用
- HDU 1885 Key Task (状态压缩+BFS)
- [Java语言] Java Socket多线程编程示例
- ABAP数据定义和类型