中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
写了下第一题
- public class MedianOccurence {
- static class Ele {
- char c ;
- int times;
- public Ele(char c, int t) {
- this.c = c;
- times = t;
- }
- }
-
- public static List<Character> getMedianOccurenceCharactr(char[] chars) {
- List<Character> res = new ArrayList<Character>();
- if (chars == null || chars.length == 0) {
- return res;
- }
- HashMap<Character, Integer> map = new HashMap<Character, Integer>();
- for (char c : chars) {
- if (map.containsKey(c)) {
- map.put(c, map.get(c) + 1);
- } else {
- map.put(c, 1);
- }
- }
- Ele[] eles = new Ele[map.size()];
- int index = 0;
- for (Entry<Character, Integer> entry : map.entrySet()) {
- eles[index++] = new Ele(entry.getKey(), entry.getValue());
- }
- int median = getMedian(eles, 0, eles.length - 1);
- for (Ele ele : eles) {
- if (ele.times == median) {
- res.add(ele.c);
- }
- }
-
- return res;
- }
- private static int getMedian(Ele[] eles, int start, int end) {
- int k = (eles.length - 1) / 2;
- int index = parition(eles, start, end);
- if (index == k) {
- return eles[index].times;
- } else if (index > k) {
- return getMedian(eles, start, index - 1);
- } else {
- return getMedian(eles, index + 1, end);
- }
- }
- private static int parition(Ele[] eles, int start, int end) {
- int pivot = start;
- int i = start;
- int j = start + 1;
- while (j <= end) {
- if (eles[j].times < eles[pivot].times) {
- i++;
- swap(eles, i, j);
- }
- j++;
- }
- swap(eles, i, pivot);
- return i;
- }
- private static void swap(Ele[] eles, int i, int j) {
- Ele tmp = eles[i];
- eles[i] = eles[j];
- eles[j] = tmp;
- }
-
- public static void main(String[] args) {
- char[] chars = {'a', 'b', 'b','c', 'c', 'c', 'e', 'e', 'e', 'd', 'd', 'd', 'd'};
- List<Character> res = getMedianOccurenceCharactr(chars);
- for (char c : res) {
- System.out.println(c);
- }
- }
-
- }
复制代码 |
|