【Hot100】LeetCode—169. 多数元素

目录

  • [1- 思路](#1- 思路)
  • [2- 实现](#2- 实现)
    • [⭐++136. 只出现一次的数字++------题解思路](#⭐136. 只出现一次的数字——题解思路)
  • [3- ACM 实现](#3- ACM 实现)


1- 思路

题目识别

  • 识别1 :统计数组中出现数量多余 [n/2] 的元素

技巧

  • 值相同,则对 count +=1,如果不相同则对值进行 count -= 1
  • 如果 count==0 ,此时更新 candidate

2- 实现

⭐++136. 只出现一次的数字++------题解思路

java 复制代码
class Solution {
    public int majorityElement(int[] nums) {
        int count = 0;
        int candidate = 0;
        for(int i : nums){
            if(count==0){
                candidate = i;
            }
            count += (i == candidate) ? 1:-1;
        }
        return candidate;
    }
}

3- ACM 实现

java 复制代码
public class majorityElement {

    public static int isCandidate(int[] nums) {
        int candidate = 0;
        int count = 0;
        for(int i: nums){
            if(count==0){
                candidate = i;
            }
            count += (i == candidate) ? 1:-1;
        }
        return candidate;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        input = input.replace("[","").replace("]","");
        String[] parts = input.split(",");
        int[] nums = new int[parts.length];
        for(int i = 0 ; i < nums.length;i++){
            nums[i] = Integer.parseInt(parts[i]);
        }
        System.out.println("结果是"+isCandidate(nums));
    }
}
相关推荐
天选之女wow11 分钟前
【代码随想录算法训练营——Day32】动态规划——509.斐波那契数、70.爬楼梯、746.使用最小花费爬楼梯
算法·leetcode·动态规划
红衣小蛇妖18 分钟前
LeetCode-704-二分查找
java·算法·leetcode·职场和发展
rongqing201923 分钟前
问题记录:一个简单的字符串正则匹配算法引发的 CPU 告警
算法
无限进步_40 分钟前
C语言字符串与内存操作函数完全指南
c语言·c++·算法
rengang661 小时前
07-逻辑回归:分析用于分类问题的逻辑回归模型及其数学原理
人工智能·算法·机器学习·分类·逻辑回归
Zzzzmo_1 小时前
【Java】杨辉三角、洗牌算法
java·数据结构·算法
闻缺陷则喜何志丹1 小时前
【C++贪心】P10537 [APIO2024] 九月|普及+
c++·算法·贪心·洛谷
QiZhang | UESTC1 小时前
JAVA算法练习题day27
java·开发语言·c++·算法·leetcode·hot100
饼干吖1 小时前
记一次滑动数组解题
java·算法
小马爱打代码1 小时前
分布式锁:原理算法和使用建议
分布式·算法