首页 > 代码库 > [leetcode] 数字游戏

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

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

public class Solution {
    public int majorityElement(int[] nums) {
        int candidate = 0;
        int count = 0;
        for (int num : nums) {
            if (count == 0) {
                candidate = num;
                count = 1;
            } else if (candidate == num) {
                count++;
            } else {
                count--;
            }
        }
        return candidate;
    }
}

 229. Majority Element II

Given an integer array of size n, find all elements that appear more than ? n/3 ? times. The algorithm should run in linear time and in O(1) space.

Hint:

  1. How many majority elements could it possibly have?

Do you have a better hint? Suggest it!

public class Solution {
    public List<Integer> majorityElement(int[] nums) {
        int candidate1 = 0, candidate2 = 0;
        int count1 = 0, count2 = 0;
        for (int num : nums) {
            if (candidate1 == num) {
                count1++;
            } else if (candidate2 == num) {
                count2++;
            } else if (count1 == 0) {
                candidate1 = num;
                count1 = 1;
            } else if (count2 == 0) {
                candidate2 = num;
                count2 = 1;
            } else {
                count1--;
                count2--;
            }
        }
        List<Integer> result = new ArrayList<Integer>();
        int length = nums.length;
        /*
        if (count1 == 0 && count2 == 0) {
            return result;
        } else if (count1 > 0 && count2 == 0) {
            result.add(candidate1);
            return result;
        } else if (count2 > 0 && count1 == 0) {
            result.add(candidate2);
            return result;
        }*/
        count1 = 0;
        count2 = 0;
        for (int num : nums) {
            if (num == candidate1) {
                count1++;
            } else if (num == candidate2) {
                count2++;
            }
        }
        if (count1 > length / 3) {
            result.add(candidate1);
        }
        if (count2 > length / 3) {
            result.add(candidate2);
        }
        return result;
    }
}

 

[leetcode] 数字游戏