题目:
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.
题解:给定majority一定存在,所以用网上学来的一次扫描算法, 用一个count和一个current表示当前的majority数,最后的current就是majority。
C++版:
class Solution { public: int majorityElement(vector<int>& nums) { int current = nums[0]; int count = 1; for(int i = 1; i < nums.size(); i++) { if(count == 0) { current = nums[i]; count++; } else { if(current == nums[i]) { count++; } else { count--; } } } return current; } };
public class Solution { public int majorityElement(int[] nums) { int count = 1; int current = nums[0]; for(int i = 1; i < nums.length; i++) { if(count == 0) { current = nums[i]; count++; } else { if(nums[i] == current) { count++; } else { count--; } } } return current; } }
class Solution: # @param {integer[]} nums # @return {integer} def majorityElement(self, nums): count = 1 current = nums[0] for i in range(1, len(nums)): if count == 0: current = nums[i] count = 1 else: if current == nums[i]: count += 1 else: count -= 1 return current