码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] 数字游戏

时间:2016-12-31 00:27:52      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:edits   edit   turn   case   line   can   anim   blank   ges   

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] 数字游戏

标签:edits   edit   turn   case   line   can   anim   blank   ges   

原文地址:http://www.cnblogs.com/Gryffin/p/6238594.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!