题解 | 数组中出现次数超过一半的数字

数组中出现次数超过一半的数字

https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param numbers int整型一维数组 
     * @return int整型
     */
    public int MoreThanHalfNum_Solution (int[] numbers) {
        int res = numbers[0],num = 1,max_num = 1;
        Arrays.sort(numbers);
        for (int i = 0; i < numbers.length - 1; i++) {
            System.out.println("max_num : " + max_num);
            if (numbers[i] == numbers[i + 1]) {
                num++;
            } else {
                num = 1;
            }
            if (num > max_num) {
                max_num = num;
                res = numbers[i];
            }
        }
        // write code here
        return res;
    }
}

全部评论

相关推荐

牛至超人:哈工大已经很棒了,不需要加括号了,然后咋没有实习经历呢?火速趁寒假整一段实习,导师不让就狠狠肘击
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务