1613. The highest frequency IP (beginner)

description

Given a string array lines, each element represents an IP address, find the IP with the highest frequency.

There is only one IP with the highest frequency for a given data

Sample

Example 1:

输入 = ["192.168.1.1","192.118.2.1","192.168.1.1"]
输出  "192.168.1.1"

Example 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"

 Code

public static String highestFrequency(String[] ipLines) {
    String ip = ipLines[0];    //初始化数组第一个为频率最高
    int totall = 1;            //初始化次数为1
    int cnn = 1;
    for (int i = 0; i < ipLines.length; i++) {
        for (int j = 0; j < ipLines.length; j++) {
            if (i == j){    //i和j相等表明都指向相同元素,不做比较
                continue;
            }
            if (ipLines[i].equals(ipLines[j])){    //ip相同cnn++
                cnn++;
            }
        }
        if (cnn > totall) {    //如果记录出新的最高频率,覆盖之前ip和次数
            ip = ipLines[i];
            totall = cnn;
        }
        cnn = 1;
    }
    return ip;
}

Guess you like

Origin blog.csdn.net/weixin_41057555/article/details/109306536