标签:
Given an array of integers, the majority number is the number that occurs more than half
of the size of the array. Find it.
Given [1, 1, 1, 1, 2, 2, 2]
, return 1
O(n) time and O(1) extra space
投票法,利用一下要找的这个数大于size的一半这个性质
public class Solution { /** * @param nums: a list of integers * @return: find a majority number */ public int majorityNumber(ArrayList<Integer> nums) { // write your code if(nums == null || nums.size() == 0) return 0; Integer result = null; int count = 0; for(int i = 0; i < nums.size(); i++){ if(result == null){ result = nums.get(i); count = 1; } else if(nums.get(i) == result){ count++; } else{ count--; if(count == 0){ result = nums.get(i); count = 1; } } } return result; } }
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5219161.html