重囗另类BBWSeⅹHD,av狼论坛,精品一卡2卡三卡4卡乱码理论,体育生gv老师浪小辉3p警察

LeetCode Majority Element -電腦資料

電腦資料 時間:2019-01-01 我要投稿
【www.ipr-jzsc.com - 電腦資料】

    Majority Element

    Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

    You may assume that the array is non-empty and the majority element always exist in the array.

    Credits:

    Special thanks to @ts for adding this problem and creating all test cases.

    找出出現次數大于數組1/2 長度次的數字,

LeetCode Majority Element

    思路:

    本題解法很多:

    1.排序后判斷第n/2個元素與首元素是否相等

    2.哈希表

    3.每次移除兩個不等的元素

    ...

    第3種方法最快,在實際應用中,哪種方式的時間復雜度都是可以接受的,這里的實現使用了第二種,即借助哈希表來完成統計,

電腦資料

LeetCode Majority Element》(http://www.ipr-jzsc.com)。

    實現代碼:

   

public class Solution {    public int MajorityElement(int[] nums) {        if(nums.Length == 0){    		return 0;    	}    	    	var hash = new Dictionary<int, int="">();    	var max = 1;    	var maxKey = nums[0];    	for(var i = 0;i < nums.Length; i++){    		if(hash.ContainsKey(nums[i])){    			hash[nums[i]] ++;    			if(max < hash[nums[i]]){    				max = hash[nums[i]];    				maxKey = nums[i];    			}    		}    		else{    			hash.Add(nums[i],1);    		}    	}    	    	return maxKey;    }}</int,>

最新文章
主站蜘蛛池模板: 涪陵区| 治多县| 广德县| 乌兰浩特市| 龙井市| 丹棱县| 基隆市| 合肥市| 花莲市| 嘉义县| 徐水县| 宜都市| 伊吾县| 隆德县| 孝义市| 盘锦市| 农安县| 延寿县| 罗田县| 当阳市| 沁源县| 石家庄市| 龙游县| 望奎县| 辽阳县| 贡嘎县| 博白县| 建阳市| 汾西县| 东莞市| 仪征市| 岢岚县| 雷州市| 金湖县| 朝阳区| 华池县| 罗山县| 柏乡县| 定边县| 宜城市| 定西市|