[LeetCode] Majority Element
2015-08-13 14:02
232 查看
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
这道题其实可以用比较取巧的方法做。因为在这里marjority element的定义是整个数列中至少一半的数字都是它,所以当我们sorting了整个数列,中间的那个数肯定是Marjority element。所以非常简单,考虑下length为1的特殊情况就可。代码如下。
当然了还有比较常规的,老实按照loop来计算的。这个思路就很简单了。代码如下。
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
这道题其实可以用比较取巧的方法做。因为在这里marjority element的定义是整个数列中至少一半的数字都是它,所以当我们sorting了整个数列,中间的那个数肯定是Marjority element。所以非常简单,考虑下length为1的特殊情况就可。代码如下。
public class Solution { public int majorityElement(int[] nums) { if(nums.length==1){ return nums[0]; } Arrays.sort(nums); return nums[nums.length/2]; } }
当然了还有比较常规的,老实按照loop来计算的。这个思路就很简单了。代码如下。
public class Solution { public int majorityElement(int[] num) { if(num.length==1){ return num[0]; } Arrays.sort(num); int test=num[0]; int count=1; for(int i=1; i<num.length; i++){ if(num[i] == test){ count++; if(count > num.length/2) return num[i]; }else{ count=1; test = num[i]; } } return 0; } }
相关文章推荐
- Java Statement和PreparedStatement性能测试(转)
- Android初体验
- 对比抽象类和接口
- Android Studio Tips -- 布局预览
- Java多线程系列--“JUC锁”08之 共享锁和ReentrantReadWriteLock
- Delphi 简体-繁体 转换函数
- 深度学习综述
- debian 安装phpredis
- IO-STEAM-基础
- 设计模式:17 适配器模式
- Threading
- 反射——1 通过反射写记事本插件
- oracle pivot
- 抽象工厂模式
- PAT 1027. Colors in Mars (20)
- linux 创建swap分区
- JVM codecache 配置
- Java中的Error和Exceptiond的异同点
- 2-3-RHEL6.3搭建NTP 服务器案例分析与总结(RedHat Enterprise Linux Server6.3)@树袋飘零
- 单例模式3-宏和MRC的严谨