package editor.cn;
/**
* /**
* /**
* ////数组中占比超过一半的元素称之为主要元素。给你一个 整数 数组,找出其中的主要元素。若没有,返回 -1 。请设计时间复杂度为 O(N) 、空间复杂度为
* //O(1
* ////) 的解决方案。
* ////
* ////
* ////
* //// 示例 1:
* ////
* ////
* ////输入:[1,2,5,9,5,9,5,5,5]
* ////输出:5
* ////
* //// 示例 2:
* ////
* ////
* ////输入:[3,2]
* ////输出:-1
* ////
* //// 示例 3:
* ////
* ////
* ////输入:[2,2,1,1,1,2,2]
* ////输出:2
* //// Related Topics 数组 计数 195 0
* //
*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
/**
* 解体思想
* 1、在数组中一次同时删掉两个不同的元素,如果存在某个数出现次数大于数组长度的一半,那么即使每次都删,最后也会至少剩下 1 个(不可能存在两个候选人,因为不可能存在两个数都超过一半);
* <p>
* 2、 采用阵地攻守的思想:第一个数字作为第一个士兵即候选人 candiate,守阵地;candiate = 1 记录候选人个数;遇到相同元素,count++; 遇到不相同元素,即为敌人,同归于尽,count- -;当遇到 count 为 0 的情况,又以新的 i 值作为守阵地的士兵,继续下去,到最后还留在阵地上的士兵,有可能是出现次数超过数组长度一半的元素。再遍历一次,确定这个士兵的个数看是否大于数组一半即可。
*
* @param nums
* @return
*/
public static int majorityElement(int[] nums) {
int candidate = 0;
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (count == 0) {
candidate = nums[i];
count++;
} else if (nums[i] == candidate) {
count++;
} else {
count--;
}
}
if (count != 0) {
count = 0;
for (int i = 0; i < nums.length; i++) {
if (candidate == nums[i]) {
count++;
}
}
if (count > nums.length / 2) {
return candidate;
}
}
return -1;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3};
System.out.println(majorityElement(nums));
}
}
//leetcode submit region end(Prohibit modification and deletion)