[LeetCode] 451. Sort Characters By Frequency 解题报告
2017-03-07 07:02
211 查看
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Example 2:
Example 3:
这一题为medium难度,但是个人感觉比较简单,可以说的不多,很显然是遍历统计次数,然后输出即可,直接上思路。
方法:
遍历整个单词,对于每个字母统计出现的顺序。针对每个字母,我使用的是一个int[][]来存储。对于一个字符,int[0]存储的是它出现的次数,遇到一次就++,int[1]存储的是该字符的index,这是为了在后面对频率排序的时候,仍然知道对应频率的字符是哪一个。(其实这个地方就是一个key value对,但是为了在结果里面排名更靠前,使用array无疑是最快的)。
遍历完以后,针对int[0]降序排列,然后按照int[1]字符,int[0]的频率,输出即可,很简单。
下面是代码,复杂度为O(n),实际运行时间大致在n到2n之间:
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.
这一题为medium难度,但是个人感觉比较简单,可以说的不多,很显然是遍历统计次数,然后输出即可,直接上思路。
方法:
遍历整个单词,对于每个字母统计出现的顺序。针对每个字母,我使用的是一个int[][]来存储。对于一个字符,int[0]存储的是它出现的次数,遇到一次就++,int[1]存储的是该字符的index,这是为了在后面对频率排序的时候,仍然知道对应频率的字符是哪一个。(其实这个地方就是一个key value对,但是为了在结果里面排名更靠前,使用array无疑是最快的)。
遍历完以后,针对int[0]降序排列,然后按照int[1]字符,int[0]的频率,输出即可,很简单。
下面是代码,复杂度为O(n),实际运行时间大致在n到2n之间:
public class Solution { public String frequencySort(String s) { char[] cArr = s.toCharArray(); // int[][]={freq,index} int[][] nArrAlphas = new int[128][2]; for (int i = 0; i < nArrAlphas.length; i++) { nArrAlphas[i][1] = i; } for (char c : cArr) { nArrAlphas[c][0]++; } Arrays.sort(nArrAlphas, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o2[0] - o1[0]; } }); StringBuilder sb = new StringBuilder(); for (int i = 0; i < nArrAlphas.length; i++) { if (nArrAlphas[i][0] > 0) { for (int j = 0; j < nArrAlphas[i][0]; j++) { sb.append((char) nArrAlphas[i][1]); } } else { break; } } return sb.toString(); } }实际上,在new int[][]的时候,可打印的字符应该不会多到128个,实际上应该少于这个值,我偷懒就直接写了128。
相关文章推荐
- [LeetCode] Integer to Roman 解题报告
- [Leetcode] 697. Degree of an Array 解题报告
- [Leetcode] 790. Domino and Tromino Tiling 解题报告
- 【LeetCode】Invert Binary Tree 解题报告
- [Leetcode] 219. Contains Duplicate II 解题报告
- 【LeetCode】Excel Sheet Column Number 解题报告
- [LeetCode]Word Ladder,解题报告
- [leetcode] 399. Evaluate Division 解题报告
- 【LeetCode】414. Third Maximum Number 解题报告
- [leetcode] 188. Best Time to Buy and Sell Stock IV 解题报告
- LeetCode: Symmetric Tree 解题报告
- 【LeetCode】Best Time to Buy and Sell Stock 解题报告
- Leetcode 400. Nth Digit 第n个数字 解题报告
- leetCode解题报告5道题(六)
- 【LeetCode】Linked List Cycle 解题报告(Java & Python)
- [leetcode] 118. Pascal's Triangle 解题报告
- [Leetcode] 233. Number of Digit One 解题报告
- [Leetcode] 529. Minesweeper 解题报告
- 【LeetCode】Trapping Rain Water解题报告
- Leetcode 129. Sum Root to Leaf Numbers 计算路径和 解题报告