169_Majority Element

来源:互联网 发布:以显示数据为准在哪里 编辑:程序博客网 时间:2024/05/06 06:32
题目地址:https://leetcode.com/problems/majority-element/

方法一:直接法

直接统计每个数的个数,Java实现如下

public class Solution {    public int majorityElement(int[] nums) {    Integer value;    HashMap<Integer,Integer> count = new HashMap<Integer,Integer>();    for(int i=0;i<nums.length;++i){    value = count.get(nums[i]);    if(value==null){    value=0;    }    if(value>=nums.length/2){    return nums[i];    }    count.put(nums[i], value+1);    }return nums[0];    }}

方法二:
思路:找到两个不同的数,把他们都划去。因为majority element 超过总数的一半,最后剩下的就是所求的数。
C++实现如下
class Solution {public:    int majorityElement(vector<int> &num) {        int nTimes = 0;        int candidate = 0;        for(int i = 0; i < num.size(); i ++)        {            if(nTimes == 0)            {                candidate = num[i];                nTimes = 1;            }            else            {                if(candidate == num[i])                    nTimes ++;                else                    nTimes --;            }        }        return candidate;    }};


0 0
原创粉丝点击