【Java】majorityElement
来源:互联网 发布:安卓4.0淘宝 编辑:程序博客网 时间:2024/05/22 00:13
/** * Created on 16/6/4. */import java.util.Arrays;import java.util.HashMap;public class majorityElement { public static void main(String[] args) { int[] x = {1,2,4,4,4,3}; System.out.println(majorityElement(x)); System.out.println(anotherMajorityElement(x)); System.out.println(thirdMajorityElement(x)); } public static int majorityElement(int[] x) { Arrays.sort(x); return x[x.length/2]; } public static int anotherMajorityElement(int[] x) { if (x == null || x.length == 0) { return 0; } int major = x[0]; int count = 1; for (int i = 1; i < x.length; i++) { if (major == x[i]) { count++; } else { count--; } if (count == 0) { major = x[i]; count = 1; } } return major; } public static int thirdMajorityElement(int[] x) { int len = x.length; if (len < 3) { return x[0]; } int m = (len % 2 == 0) ? len / 2 : len / 2 + 1; HashMap<Integer, Integer> map = new HashMap<>(); for (int key : x) { if (!map.containsKey(key)) { map.put(key, 1); } else { int count = map.get(key); if (count + 1 > m) { return key; } map.put(key, count + 1); } } return 0; }}
0 0
- 【Java】majorityElement
- MajorityElement
- java实现算法之MajorityElement
- 169MajorityElement
- leetcode MajorityElement相关问题
- java
- JAVA
- JAVA
- JAVA
- java
- Java
- Java
- JAVA:
- java
- java
- java
- java
- Java
- Tamura纹理特征的matlab实现
- c++关于函数的按值传递和按址传递
- 机器学习-KMeans聚类 K值以及初始类簇中心点的选取
- 第2.7节 类型转换——表达式中float类型的操作数不会自动转化为double类型等
- MarkDown环境的配置-mac
- 【Java】majorityElement
- DexIndexOverflowException: Cannot merge new index 65772 into a non-jumbo instruction
- 跟随屏幕大小自动调整bitmap大小(横竖屏拍摄的照片均可)
- com.android.dex.DexIndexOverflowException
- CentOS7手动释放内存
- sql 面试题
- UVA 10000 - Longest Paths
- 3. Spring Boot热部署【从零开始学Spring Boot】
- Python学习笔记 —— 逻辑语句