【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));
    }
}
相关推荐
君义_noip1 小时前
信息学奥赛一本通 1607:【 例 2】任务安排 2 | 洛谷 P10979 任务安排 2
算法·动态规划·信息学奥赛·斜率优化
因兹菜1 小时前
[LeetCode]day4 977.有序数组的平方
数据结构·算法·leetcode
weixin_537590452 小时前
《C程序设计》第六章练习答案
c语言·c++·算法
码农小苏242 小时前
K个不同子数组的数目--滑动窗口--字节--亚马逊
java·数据结构·算法
独自破碎E2 小时前
【4】阿里面试题整理
java·开发语言·算法·排序算法·动态规划
涛ing8 小时前
32. C 语言 安全函数( _s 尾缀)
linux·c语言·c++·vscode·算法·安全·vim
独正己身8 小时前
代码随想录day4
数据结构·c++·算法
利刃大大11 小时前
【回溯+剪枝】找出所有子集的异或总和再求和 && 全排列Ⅱ
c++·算法·深度优先·剪枝
Rachela_z12 小时前
代码随想录算法训练营第十四天| 二叉树2
数据结构·算法
细嗅蔷薇@12 小时前
迪杰斯特拉(Dijkstra)算法
数据结构·算法