給定一個字符數組,例如char[] chars = { 'a', 'b', 'b', 'b', 'b', 'c', 'a', 'a', 'a'};
找出數組中出現次數最多的字符,若是存在相同次數的字符,取出現較早者。
一個問題的解決方案有多種:java
利用數據結構的特性,鏈表保證了插入順序,Map正是咱們想要的字符與出現次數對應關係的映射,代碼以下,只需遍歷一次數組
char[] chars = {'a', 'b', 'b', 'b', 'b', 'c', 'a', 'a', 'a'}; Map<Character, Integer> countMap = new LinkedHashMap<>(); Map<Character, Integer> indexMap = new LinkedHashMap<>(); int length = chars.length; // 目標字符 char target = 0; // 出現的最屢次數 int maxCount = 0; for (int index = 0; index < length; index++) { char aChar = chars[index]; Integer value = countMap.get(aChar); if (value == null) { // 若是已經存在某字符 maxCount 比數組剩餘待遍歷元素數量還多,不必考慮它了 if (maxCount > length - (index + 1)) { break; } countMap.put(aChar, 1); indexMap.put(aChar, index); } else { countMap.put(aChar, value += 1); if (maxCount == value) { // 出現相同次數的 char,取先在數組中出現的 // 即誰出現的次數 + 出現的 index 小 // 也能夠將 value 封裝成含有索引和次數的對象,那樣只需聲明一個 map if (indexMap.get(aChar) < indexMap.get(target)) { target = aChar; } } else if (maxCount < value) { maxCount = value; target = aChar; } } }
將原數組拷貝成orderedChars
而後排序,接着遍歷查找orderedChars
和originalChars
,操做比較麻煩,不推薦,可是能夠鍛鍊純數組操做和「指針」的使用數據結構
char[] originalChars = {'a', 'a', 'c', 'b', 'b', 'b', 'c', 'b', 'c', 'c', 'a', 'd', 'd', 'd'}; int length = originalChars.length; // 拷貝原數組,並排序 char[] orderedChars = new char[length]; System.arraycopy(originalChars, 0, orderedChars, 0, length); Arrays.sort(orderedChars); // 最大次數 尋找的字符,給個默認值 int maxCount = 1; char target = orderedChars[0]; int headIndex = 0, tailIndex = 1, targetIndex = -1; for (; tailIndex < length; ) { // 移動 tailIndex 的時候 headIndex 不動 // tailIndex++ == (length - 1) 特殊處理 orderedChars 最後幾位都是同一 char 的狀況 if (orderedChars[headIndex] != orderedChars[tailIndex] || (tailIndex++ == (length - 1))) { // 臨時計數器 int tmpCount = tailIndex - headIndex; if (tmpCount < maxCount) { // 已找到出現次數最多的char 即 headIndex 的上一個 target = orderedChars[headIndex - 1]; break; } else if (tmpCount > maxCount) { maxCount = tmpCount; target = orderedChars[headIndex]; } else { // 若是遇到相同次數的就比較麻煩了 // 須要在原數組中比較誰先出現,即索引更小者 int tmpCurIndex = -1; for (int i = 0; i < length; i++) { if (originalChars[i] == target && targetIndex == -1) { targetIndex = i; } else if (originalChars[i] == orderedChars[headIndex] && tmpCurIndex == -1) { tmpCurIndex = i; } if (tmpCurIndex != -1 && targetIndex != -1) { if (tmpCurIndex < targetIndex) { targetIndex = tmpCurIndex; target = originalChars[targetIndex]; } break; } } } // 在日後找的過程當中,若是找到知足條件的就將 headIndex 移至tailIndex,即 headIndex = tailIndex // tailIndex 繼續移動,即 ++ 操做 headIndex = tailIndex; } }