bloggerads

2016年6月3日 星期五

LeetCode : 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.


// C++ Solution

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        if (nums.size() == 1) return nums[0];
        map <int, int> m;
        for (int i=0; i<nums.size(); i++) {
            if (m.find(nums[i]) == m.end() )
                m[nums[i]] = 1;
            else {
                m[nums[i]]++;
                if (m[nums[i]] > nums.size()/2)
                    return nums[i];
            }
        }
    }
};

// C# Solution

public class Solution {
    public int MajorityElement(int[] nums) {
            var map = new Dictionary<int, int>();
            for (int i = 0; i < nums.Length; i++)
            {
                int mapValue;
                if (map.TryGetValue(nums[i], out mapValue))
                {
                    map[nums[i]]++;
                }
                else
                {
                    map.Add(nums[i], 1);
                }
            }
            int BiggestValue = 0;
            int BiggestKey = 0;
            foreach (var pair in map)
            {
                if (pair.Value > BiggestValue)
                {
                    BiggestValue = pair.Value;
                    BiggestKey = pair.Key;
                }
            }
            return BiggestKey;
    }
}

沒有留言:

張貼留言