leetcode 169. 多数元素

 给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

 你可以假设数组是非空的,并且给定的数组总是存在多数元素。

package Bean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


public class Test {

    public int majorityElement(int[] nums){

            int n = nums[0];

            int count = 1;

            for(int num : nums) {

                if(num != n) {

                    count--;

                    if(count == 0) {

                        count = 1;

                        n = num;

                    }
                }

                else count++;

            }
            return n;
        }




    public static void main(String[] args) {


        int[] num = {2,2,1,1,2,2,1};

        Test t= new Test();

        int n =  t.majorityElement(num);

        System.out.println(n);

    }
}

发布了8 篇原创文章 · 获赞 0 · 访问量 125

猜你喜欢

转载自blog.csdn.net/cypherO_O/article/details/104406050