[leetcode] 数字游戏

Posted 冬日焰火

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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] 数字游戏的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 299 猜数字游戏[遍历] HERODING的LeetCode之路

LeetCode - 390 -消除游戏 - Java - 细喔

Leetcode-299 猜数字游戏

leetcode打卡——299. 猜数字游戏(求交集or标记法)

猜数字小游戏

LeetCode-299. 猜数字游戏