首页 > 其他 > 详细

Leetcode problem-169 Majority Element 题解

时间:2016-11-14 15:36:24      阅读:228      评论:0      收藏:0      [点我收藏+]

Leetcode Problem-169 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.

题解:题目已经肯定主元素一定存在,且出现次数大于n/2,数组又假定已经非空。采用分治法,每找到两个不同的元素,则成对删除,最终剩下的一定就是所求的。

class Solution {

public:

    int majorityElement(vector<int>& nums) {

        int most = 0;

        int cnt = 0;

        for(int i=0;i<nums.size();i++)

        {

            if(cnt==0)

            {

                most=nums[i];

                cnt++;

            }

            else

            {

                if(nums[i]==most)

                {

                    cnt++;

                }

                else

                {

                    cnt--;

                }

            }

           

        }

        return most;

    }

};

Leetcode problem-169 Majority Element 题解

原文:http://www.cnblogs.com/fengxw/p/6061602.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!