[LeetCode BY Python]169. Majority Element
2018-02-07 14:07
393 查看
题目:
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
解释:
这里我用了一个字典,记录每个数字出现的次数
代码:
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = {}
nums_mid = len(nums)/2
for i in nums:
if i in ans.keys():
ans[i]+=1
else:
ans[i] = 1
if ans[i]>nums_mid:
return i
return None
a = Solution()
print a.majorityElement([2,3,4,5,2,2])
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.
解释:
这里我用了一个字典,记录每个数字出现的次数
代码:
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = {}
nums_mid = len(nums)/2
for i in nums:
if i in ans.keys():
ans[i]+=1
else:
ans[i] = 1
if ans[i]>nums_mid:
return i
return None
a = Solution()
print a.majorityElement([2,3,4,5,2,2])
相关文章推荐
- [Leetcode By Python]69. Sqrt(x)
- [leetCode By python]104. Maximum Depth of Binary Tree
- [LeetCode By Python]108. Convert Sorted Array to Binary Search Tree
- [LeetCode By Python]118. Pascal's Triangle
- [leetcode By Python]strStr
- [LeetCode By Python]58. Length of Last Word
- [LeetCode By Python]172. Factorial Trailing Zeroes
- [LeetCode By Python]83. Remove Duplicates from Sorted List
- [LeetCode BY Python]160. Intersection of Two Linked Lists
- [LeetCode By Python]66. Plus One
- [LeetCode By Python]7 Reverse Integer
- [leetCode By Python]100. Same Tree
- [leetCode By Python] 14. Longest Common Prefix
- [LeetCode By Python]119. Pascal's Triangle II
- [LeetCode By Python]67. Add Binary
- [LeetCode By Python]121. Best Time to Buy and Sell Stock
- [LeetCode By Python]53. Maximum Subarray
- [LeetCode By Python]122. Best Time to Buy and Sell Stock II
- [LeetCode By Python]27. Remove Element
- [LeetCode By python]35. Search Insert Position