Given an array of integers, the majority number is the number that occurs more than half
of the size of the array. Find it.
Example
Given [1, 1, 1, 1, 2, 2, 2]
, return 1
Challenge
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; } }
时间: 2024-10-19 23:28:00