当前位置: 代码迷 >> 综合 >> 【Lintcode】1613. Highest frequency IP
  详细解决方案

【Lintcode】1613. Highest frequency IP

热度:83   发布时间:2024-02-06 05:01:18.0

题目地址:

https://www.lintcode.com/problem/highest-frequency-ip/description

给定一个字符串数组,求其中出现最多的那个字符串。题目保证答案唯一。用一个哈希表存每个字符串出现了多少次,同时用一个int变量记录出现最多的次数。遍历完后将哈希表里出现次数最多的那个字符串挑出来即可。代码如下:

import java.util.HashMap;
import java.util.Map;public class Solution {/*** @param ipLines: ip address* @return: return highestFrequency ip address*/public String highestFrequency(String[] ipLines) {// Write your code hereint maxFrequency = 0;Map<String, Integer> frequencies = new HashMap<>();for (String ipLine : ipLines) {frequencies.put(ipLine, frequencies.getOrDefault(ipLine, 0) + 1);maxFrequency = Math.max(frequencies.get(ipLine), maxFrequency);}for (Map.Entry<String, Integer> entry : frequencies.entrySet()) {if (entry.getValue() == maxFrequency) {return entry.getKey();}}return "";}
}

时空复杂度 O ( n ) O(n)