首页 > 代码库 > [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:
- 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] 数字游戏
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。