【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));
    }
}
相关推荐
EllinY19 分钟前
CF2217E Definitely Larger 题解
c++·笔记·算法·构造
玖釉-4 小时前
下一个排列:从字典序到原地算法的完整推导
数据结构·c++·windows·算法
IronMurphy4 小时前
【算法五十】62. 不同路径
算法
影寂ldy4 小时前
C#一维数组
算法
过期动态4 小时前
【LeetCode 热题 100】移动零
java·数据结构·算法·leetcode·职场和发展·rabbitmq
计算机安禾5 小时前
【算法分析与设计】第10篇:下界理论与NP完全性初步
大数据·人工智能·算法
水木流年追梦6 小时前
大模型入门-大模型分布式训练2
开发语言·分布式·python·算法·正则表达式·prompt
sali-tec6 小时前
C# 基于OpenCv的视觉工作流-章78-KRT测量
图像处理·人工智能·数码相机·opencv·算法·计算机视觉
菜菜的顾清寒6 小时前
力扣HOT100(32)二叉树的中序遍历
数据结构·算法·leetcode