标签:
Majority Element
问题:
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.
思路:
超过半数的总会剩余
我的代码:
public class Solution { public int majorityElement(int[] num) { if(num == null || num.length == 0) return -1; Stack<Integer> stack = new Stack<Integer>(); for(int i = 0; i < num.length; i++) { if(stack.isEmpty()) stack.push(num[i]); else { int top = stack.peek(); if(top == num[i]) stack.push(num[i]); else stack.pop(); } } return stack.pop(); } }
他人代码:
public class Solution { public int majorityElement(int[] num) { int maj=0; int count = 0; int n = num.length; for (int i = 0; i < n; i++){ if (count == 0){ maj = num[i]; count++; } else if (num[i] == maj){ count++; if (count > n/2) return maj; } else count--; } return maj; } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4318565.html