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、我是利用字典,空间复杂度较高,遍历列表,如果已经该元素已经存在于字典中,那么键值+1,否则创建键值对,并且每次遍历比较最大键值m,并保留该值的对应元素n,最后返回n

    2、大神就只用了一个变量count计数,因为有超过一半的数都是该值,所以count==0那儿,到最后count不会小于等于0

  代码:

    我的:

 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

    大神:

    

 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 }

 

posted @ 2017-09-19 12:04  唐僧洗发爱飘柔  阅读(97)  评论(0)    收藏  举报