【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));
    }
}
相关推荐
你也向往长安城吗1 小时前
推荐一个三维导航库:three-pathfinding-3d
javascript·算法
百度智能云1 小时前
VectorDB+FastGPT一站式构建:智能知识库与企业级对话系统实战
算法
AI小白的Python之路2 小时前
数据结构与算法-排序
数据结构·算法·排序算法
DashVector2 小时前
如何通过Java SDK检索Doc
后端·算法·架构
zzz9332 小时前
transformer实战——mask
算法
一只鱼^_3 小时前
牛客周赛 Round 105
数据结构·c++·算法·均值算法·逻辑回归·动态规划·启发式算法
是阿建吖!3 小时前
【动态规划】斐波那契数列模型
算法·动态规划
啊阿狸不会拉杆3 小时前
《算法导论》第 27 章 - 多线程算法
java·jvm·c++·算法·图论
火车叨位去19493 小时前
力扣top100(day04-05)--堆
算法·leetcode·职场和发展
数据智能老司机3 小时前
面向企业的图学习扩展——面向图的传统机器学习
算法·机器学习