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.app

也就是找數組中出現次數大於一半的數字,題目保證這個數字存在。spa

方法一:位操做

針對數組中每個數的每一位,計算每一位上0和1出現的次數,取出現多的做爲最終數字的當前位。code

代碼以下:時間複雜度32n=O(n),空間複雜度O(1)blog

// bit操做
    public int majorityElement(int[] nums) {
        int temp = 0, ans = 0, count0 = 0, count1 = 0;
        for (int i = 0; i < 32; i++) {
            count0 = 0;
            count1 = 0;
            for (int j = 0; j < nums.length; j++) {
                if (((nums[j] >>> i) & 1) == 1)
                    count1++;
                else
                    count0++;
            }
            if (count1 > count0)
                temp += 1;
            if (i < 31)
                temp >>>= 1;
        }
        for (int i = 0; i < 32; i++) {
            ans += ((temp >> i) & 1);
            if (i < 31)
                ans <<= 1;
        }
        return temp;
    }

 

方法二:HashMap,

空間複雜度O(n),時間複雜度O(n),相對位操做更耗時。element

// 使用hashMap
    public int majorityElement(int[] nums) {
        int temp = 0, ans = 0, count0 = 0, count1 = 0;
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            countMap.put(nums[i], countMap.getOrDefault(nums[i], 0) + 1);
            if (countMap.get(nums[i]) > nums.length / 2)
                return nums[i];
        }
        return 0;
    }

方法三:計數法,

這個方法應該是最優解法吧。相比位操做更好。get

該方法的思路是從局部思考問題,前2K個數字中,某個數沒法作成majority element,但它也有可能出現不少次,可是最終在某個點上會被其餘不相同的數字中和了。從後面再計數。最終找到的就是majority element。(描述的很差,直接看代碼理解吧)。hash

假設被中和的是majority element,不用擔憂,由於你幹掉了和你同樣多的對手,在後續的子數組中,你仍是大頭。it

假設被中和的不是,那麼後續子數組中,你仍是不能。class

代碼以下:

public int majorityElement(int[] nums) {
        int count = 0;
        int ans = nums[0];
        for (int i : nums) {
            if (count == 0)
                ans = nums[i];
            if (ans == nums[i])
                count++;
            else
                count--;
        }
        return ans;
    }
相關文章
相關標籤/搜索