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 }
相关文章
相关标签/搜索