169. Majority Element (寻找多数元素)

你的名字 2022-07-15 01:20 281阅读 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.

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

发表评论

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

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

相关阅读

    相关 169. 多数元素

    给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。 示例