标签:
题目:
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.
解决方案:Runtime: 229 ms
public class Solution { //学习网上方法,每找出两个不同的,则成对删除,最后剩余的就是所求元素 public int majorityElement(int[] num) { int count = 0; int maj = 0; for(int i = 0; i < num.length; i++){ if(count == 0){ maj = num[i]; count++; }else{ if(maj == num[i]){ count ++; if(count > num.length/2) return maj; }else{ count --; } } } return maj; } }
总结:这个方法是我从网上看到的,也是大部分人的做法,刚开始做没想到这个方法,还想着用数组去做,但是那样太复杂了。这个方法值得学习。
标签:
原文地址:http://www.cnblogs.com/Pillar/p/4309065.html