【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));
    }
}
相关推荐
拳里剑气5 小时前
C++算法:BFS解决FloodFill算法
c++·算法·bfs·宽度优先
wanderist.7 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
稚南城才子,乌衣巷风流7 小时前
支配树(Dominator Tree)详解:概念、算法与应用
算法
稚南城才子,乌衣巷风流8 小时前
动态开点:原理、实现与应用场景
数据结构·算法
yyds_yyd_100868 小时前
1464. 数组中两元素的最大乘积(2026.07.27)
数据结构·c++·算法·leetcode
KaMeidebaby9 小时前
卡梅德生物技术快报 | 核酸适配体文库测序:核酸适配体文库测序的技术原理、实验流程与数据解析
前端·网络·数据库·人工智能·算法
geovindu10 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
ekkoalex11 小时前
训练框架以及算法实现的框架
算法
DFT计算杂谈11 小时前
交错磁研究进展材料物性与交叉应用
数据库·人工智能·python·opencv·算法