国产探花免费观看_亚洲丰满少妇自慰呻吟_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;    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 武冈市| 乐安县| 昂仁县| 故城县| 丁青县| 井研县| 广平县| 博白县| 宣化县| 绥宁县| 陆川县| 郧西县| 安仁县| 华容县| 临沭县| 汉源县| 平武县| 崇信县| 乃东县| 巩义市| 桃园市| 喜德县| 张家界市| 宣恩县| 信阳市| 潼关县| 尼木县| 怀远县| 蓝田县| 观塘区| 方正县| 平原县| 正阳县| 石城县| 新泰市| 潞城市| 文成县| 富民县| 阳东县| 康乐县| 仁寿县|