【Leetcode】Majority Element

来源:互联网 发布:福建网络继续教育学院 编辑:程序博客网 时间:2024/06/06 19:34

题目链接:https://leetcode.com/problems/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.

思路:

考研的时候王道数据结构习题上有这题,求主元素,原来王道是从leetcode抄的 = =

算法:

// 采用抵消的思路public int majorityElement(int[] nums) {int mje = 0, count = 0;for (int i = 0; i < nums.length; i++) {if (count == 0) {mje = i;// count为0的时候,令当前值为主元素count++;} else { // 当前有候选主元素的时候if (nums[mje] != nums[i]) {// 抵消非候选主元素count--;} else {count++;}}}return nums[mje];}


0 0
原创粉丝点击