169. Majority Element

LeetCode Majority Element【Easy】

  • 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.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

解決

題目的意思是給定一個給定的數(shù)組中,找出多數(shù)的元素,假定數(shù)組長度為n,則這個多數(shù)元素定義為該元素在數(shù)組中出現(xiàn)的次數(shù)大于[n/2]次。
這里給出兩種解決辦法,代碼和部分的注釋如下。

hash法

 /**
   * 使用map key 存儲數(shù)組,value 統(tǒng)計出現(xiàn)的次數(shù)
   * @param nums
   * @return
   */
  public int majorityElement(int[] nums) {
      Map<Integer,Integer> map = new HashMap<>();
      int res =0;
      for(int i:nums){
          map.put(i,map.get(i)==null?1:map.get(i).intValue()+1);
          if(map.get(i).intValue()>(nums.length/2)){
              res=i;
          }

      }
      return res;
  }

數(shù)組方法

 /**
     * 排序,取數(shù)組mid,最后返回num[mid]值即為結(jié)果
     * @param nums
     * @return
     */
    public int majorityElement2(int[] nums) {
        Arrays.sort(nums);
        int t = nums.length/2;
        return nums[t];
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評論 0 10
  • Description Given an array of size n, find the majority e...
    Nancyberry閱讀 179評論 0 0
  • MicrosoftOffice2003+以前的版本,默認(rèn)格式:.doc (Word) .xls (Excel) ....
    鹽果兒閱讀 3,050評論 0 2
  • 說起來真的是罪過,小學(xué)時期每一次清明節(jié)我都感覺像是春游,少有肅穆追懷的氛圍。 那時,每逢清明,學(xué)校會安排烈...
    凌嶺閱讀 381評論 0 1
  • 清明獨酌小記 沽清末 憶先人 影如漫天紙灰有形而無相 在心頭卻又若陽光下紙上墨跡 斑駁的刺眼 孤傷 穿腸而過的黃湯...
    移步觀景閱讀 268評論 0 0

友情鏈接更多精彩內(nèi)容