国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

[LeetCode] Majority Element

2019-11-15 01:07:40
字體:
來源:轉載
供稿:網友
[LeetCode] Majority Element

Given an array of sizen, 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.

這道題其實可以用比較取巧的方法做。因為在這里marjority element的定義是整個數列中至少一半的數字都是它,所以當我們sorting了整個數列,中間的那個數肯定是Marjority element。所以非常簡單,考慮下length為1的特殊情況就可。代碼如下。

public class Solution {    public int majorityElement(int[] nums) {        if(nums.length==1){            return nums[0];        }                Arrays.sort(nums);        return nums[nums.length/2];    }}

當然了還有比較常規的,老實按照loop來計算的。這個思路就很簡單了。代碼如下。

public class Solution {    public int majorityElement(int[] num) {        if(num.length==1){            return num[0];        }         Arrays.sort(num);         int test=num[0];        int count=1;        for(int i=1; i<num.length; i++){            if(num[i] == test){                count++;                if(count > num.length/2)                 return num[i];            }else{                count=1;                test = num[i];            }        }         return 0;    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 商丘市| 故城县| 兰州市| 固始县| 思茅市| 桑植县| 札达县| 兴宁市| 文登市| 赫章县| 漾濞| 枣庄市| 淳化县| 拜城县| 瑞金市| 栾川县| 呼和浩特市| 满城县| 天津市| 河东区| 乐安县| 公主岭市| 克什克腾旗| 杭州市| 襄垣县| 岳池县| 东乌珠穆沁旗| 平果县| 富阳市| 建湖县| 绵竹市| 于田县| 长宁区| 东平县| 当涂县| 芜湖县| 印江| 南安市| 三江| 农安县| 扬州市|