leetcode4-majorityElement

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)

posted @   小傻孩丶儿  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2021-03-02 字符串总结,主要是kmp与双指针
2020-03-02 Lc175_组合俩个表_二刷
2020-03-02 Lc206_反转链表
点击右上角即可分享
微信分享提示