【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));
    }
}
相关推荐
.普通人30 分钟前
c语言--力扣简单题目(链表的中间节点)讲解
c语言·leetcode·链表
西农小陈39 分钟前
python-字符排列问题
数据结构·python·算法
TechQuester1 小时前
OpenAI 刚刚推出 o1 大模型!!突破LLM极限
人工智能·python·gpt·算法·chatgpt
__AtYou__1 小时前
Golang | Leetcode Golang题解之第412题Fizz Buzz
leetcode·golang·题解
西农小陈1 小时前
python-简单的数据结构
数据结构·python·算法
_Chocolate1 小时前
十大排序(一):冒泡排序
c语言·数据结构·算法
running thunderbolt2 小时前
C++:类和对象全解
c语言·开发语言·c++·算法
小陈的进阶之路3 小时前
c++刷题
开发语言·c++·算法
model20053 小时前
sahi目标检测java实现
java·算法·目标检测
源代码•宸4 小时前
Leetcode—322. 零钱兑换【中等】(memset(dp,0x3f, sizeof(dp))
c++·算法·leetcode·职场和发展·dp