leetcode解题之347. Top K Frequent Elements &451. Sort Characters By Frequency

来源:互联网 发布:最优化方法 答案 编辑:程序博客网 时间:2024/06/05 16:08

347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n logn), wheren is the array's size.
给定一个数组,返回数组中出现此多最多的k个元素,要求时间复杂度小于O(nlogn)。

// 利用哈希map统计频次及其对应数字// 根据频次(及其对应数字)建立最大堆public List<Integer> topKFrequent(int[] nums, int k) {HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();// 统计频率for (int num : nums) {map.put(num, map.containsKey(num) ? map.get(num) + 1 : 1);}// 自定义PriorityQueue最大堆,对map的value降序排序PriorityQueue<Map.Entry<Integer, Integer>> min = new PriorityQueue<Map.Entry<Integer, Integer>>(new Comparator<Map.Entry<Integer, Integer>>() {public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {return o2.getValue() - o1.getValue();}});// 加入所有min.addAll(map.entrySet());List<Integer> ret = new ArrayList<Integer>();for (int i = 0; i < k; i++) {// 有可能k的输入过大if (!min.isEmpty())ret.add(min.poll().getKey());}return ret;}

451. Sort Characters By Frequency

Given a string, sort it in decreasing order based on the frequency of characters.

    Example 1:
    Input:
    "tree"
    Output:
    "eert"
    Explanation:
    'e' appears twice while 'r' and 't' both appear once.
    So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
    Example 2:
    Input:
    "cccaaa"
    Output:
    "cccaaa"
    Explanation:
    Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
    Note that "cacaca" is incorrect, as the same characters must be together.
    Example 3:

    Input:
    "Aabb"
    Output:
    "bbAa"
    Explanation:
    "bbaA" is also a valid answer, but "Aabb" is incorrect.
    Note that 'A' and 'a' are treated as two different characters.

    1:统计每个字母和出现相应次数;
     2:把字母和出现次数的相应关系储存到list里;
     3:按出现次数把第二步list里的相应关系按降序排列;
     4:对于相应关系,StringBuffer,转成String输出。

public String frequencySort(String s) {if (s == null || s.length() == 0)return s;//统计词频HashMap<Character, Integer> map = new HashMap<>();for (int i = 0; i < s.length(); i++) {Character letter = s.charAt(i);if (map.containsKey(letter))map.put(letter, map.get(letter) + 1);elsemap.put(letter, 1);}List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());//自定义排序Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {@Overridepublic int compare(Entry<Character, Integer> o1,Entry<Character, Integer> o2) {return o2.getValue() - o1.getValue();}});//加入StringBufferStringBuffer sb = new StringBuffer();for (Entry<Character, Integer> e : list)for (int i = 0; i < e.getValue(); i++)sb.append(e.getKey());return sb.toString();}





0 0
原创粉丝点击