1613. 最高频率的IP

题目

给定一个字符串数组lines, 每一个元素代表一个IP地址,找到出现频率最高的IP。

样例
样例1:

输入 = ["192.168.1.1","192.118.2.1","192.168.1.1"]
输出 "192.168.1.1"
样例2:

输入 = ["192.168.1.1","192.118.2.1","192.168.1.1","192.118.2.1","192.118.2.1"]
输出 "192.118.2.1"
注意事项
给定数据只有一个频率最高的IP

思路

利用Map<String, Integer>即可

代码

public class Solution {
    /**
     * @param ipLines: ip  address
     * @return: return highestFrequency ip address
     */
    public String highestFrequency(String[] ipLines) {
        // Write your code here
        int len = ipLines.length;
        int value = 0;
        int max = 1;
        String str = null;
        
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            //如果再次出现
            if (map.containsKey(ipLines[i])) {
                value = map.get(ipLines[i]);
                map.put(ipLines[i], value+1);
                if (value +1 > max) {
                    max = value +1;
                    str = ipLines[i];
                }
            } else { //第一次出现
                map.put(ipLines[i], 1);
            }
        }
        if(str != null) {
            return str;
        } else {
            return ipLines[0];
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/twodoge/p/11742320.html