LeetCode : 169. Majority Element 众数

ゞ 浴缸里的玫瑰 2021-06-24 16:11 455阅读 0赞

试题
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.

Example 1:

Input: [3,2,3]
Output: 3
Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2
代码
随机加验证:

  1. class Solution {
  2. public int majorityElement(int[] nums) {
  3. Random rand = new Random();
  4. int max = nums.length/2;
  5. while(true){
  6. int can = nums[rand.nextInt(nums.length)];
  7. if(valid(nums, can, max)){
  8. return can;
  9. }
  10. }
  11. }
  12. public boolean valid(int[] nums, int can, int max){
  13. int count = 0;
  14. for(int n: nums){
  15. if(n==can) count++;
  16. if(count>max) return true;
  17. }
  18. return false;
  19. }
  20. }

消除法:

  1. class Solution {
  2. public int majorityElement(int[] nums) {
  3. int num=0,count=0;
  4. for(int n: nums){
  5. if(count==0){
  6. num = n;
  7. count++;
  8. continue;
  9. }
  10. if(n==num){
  11. count++;
  12. }else{
  13. count--;
  14. }
  15. }
  16. return num;
  17. }
  18. }

发表评论

表情:
评论列表 (有 0 条评论,455人围观)

还没有评论,来说两句吧...

相关阅读