Majority Element

    這道題爲簡單題app

  題目:

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

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

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

  思路:

    一、我是利用字典,空間複雜度較高,遍歷列表,若是已經該元素已經存在於字典中,那麼鍵值+1,不然建立鍵值對,而且每次遍歷比較最大鍵值m,並保留該值的對應元素n,最後返回nblog

    二、大神就只用了一個變量count計數,由於有超過一半的數都是該值,因此count==0那兒,到最後count不會小於等於0ci

  代碼:

    個人:element

 1 class Solution(object):
 2     def majorityElement(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         a = {}
 8         m = 0
 9         n = 0
10         for i in nums:
11             if i in a:
12                 a[i] += 1
13             else: a[i] = 1
14             if a[i] > m:
15                 m = a[i]
16                 n = i
17         return n

    大神:leetcode

    

 1 public class Solution {
 2     public int majorityElement(int[] num) {
 3 
 4         int major=num[0], count = 1;
 5         for(int i=1; i<num.length;i++){
 6             if(count==0){
 7                 count++;
 8                 major=num[i];
 9             }else if(major==num[i]){
10                 count++;
11             }else count--;
12             
13         }
14         return major;
15     }
16 }
相關文章
相關標籤/搜索