【LeetCode-口试算法经典-Java实现】【169-Majority Element(主元素)】
【LeetCode-面试算法经典-Java实现】【169-Majority Element(主元素)】
【169-Majority Element(主元素)】
【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
代码下载【https://github.com/Wang-Jun-Chao】
原题
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.
题目大意
给定一个数组,找这个数组中的主元素,主元素是元素出现次数大于⌊ n/2 ⌋的元素。
假设给定的数组非空,主元素都存在。
解题思路
用一个标记cnt记录某个元素出现的次数,如果后面的元素和它相同就加一,有一个元素和他不相同就减一,当cnt小于等于0时重新记录新的元素。
代码实现
算法实现类
public class Solution {
public int majorityElement(int[] num) {
int main = num[0]; // 用于记录主元素,假设第一个是主元素
int count = 1; // 用于抵消数的个数
for (int i = 1; i < num.length; i++) { // 从第二个元素开始到最后一个元素
if (main == num[i]) { // 如果两个数相同就不能抵消
count++; // 用于抵消的数据加1
} else {
if (count > 0) { // 如果不相同,并且有可以抵消的数
count--; // 进行数据抵消
} else { // 如果不相同,并且没有可以抵消的数
main = num[i]; // 记录最后不可以抵消的数
}
}
}
// 对于数组中可能没有主元素的情况,题中说明存在,此步可以省略。
// count = 0;
// for (int a : num) {
// if (a == main) {
// count++;
// }
// }
//
// if (count >= num.length / 2) {
// return main;
// } else {
// throw new RuntimeException("No majority element");
// }
return main;
}
}
评测结果
点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。
特别说明
欢迎转载,转载请注明出处【http://blog.****.net/derrantcm/article/details/47902549】
版权声明:本文为博主原创文章,未经博主允许不得转载。