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

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

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

using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param numbers int整型一维数组
     * @return int整型
     */
    public int MoreThanHalfNum_Solution (List<int> numbers) {
        // write code here
        int len = numbers.Count / 2;
        Dictionary<int, int> dic = new Dictionary<int, int>();
        for (int i = 0; i < numbers.Count; i++) {
            if (dic.ContainsKey(numbers[i])) {
                dic[numbers[i]] += 1;
            } else {
                dic.Add(numbers[i], 1);
            }
        }
        foreach (var item in dic) {
            if (item.Value > len) {
                return item.Key;
            }
        }
        return -1;
    }
}

全部评论

相关推荐

12-13 14:51
已编辑
井冈山大学 算法工程师
龙虾x:算法比你强的没有你美,比你美的…..算了已经没有比你美的了
工作两年想退休了
点赞 评论 收藏
分享
牛客36400893...:我不是这个专业的,但是简历确实没有吸引我的亮点,而且废话太多没耐心看
0offer是寒冬太冷还...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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