From 4af3ecb2eacbe10361fe419f981dea30a93112bf Mon Sep 17 00:00:00 2001 From: Yunchang Cheng <272410181@qq.com> Date: Sat, 24 Sep 2022 15:45:36 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A4=9A=E6=95=B0=E5=85=83=E7=B4=A0=E2=80=94?= =?UTF-8?q?=E2=80=94Java=E7=89=88=E6=8A=95=E7=A5=A8=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Code by Java --- problems/169.majority-element.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/problems/169.majority-element.md b/problems/169.majority-element.md index 65649a26a..052d5a20b 100644 --- a/problems/169.majority-element.md +++ b/problems/169.majority-element.md @@ -54,7 +54,7 @@ https://leetcode-cn.com/problems/majority-element/ ## 代码 -- 语言支持:JS,Python, CPP +- 语言支持:JS,Python, CPP,Java Javascript Code: @@ -112,6 +112,26 @@ public: }; ``` +Java Code: + +```java +class Solution { + public int majorityElement(int[] nums) { + int count = 0; + Integer candidate = null; + + for (int num : nums) { + if (count == 0) { + candidate = num; + } + count += (num == candidate) ? 1 : -1; + } + + return candidate; + } +} +``` + **复杂度分析** - 时间复杂度:$O(N)$,其中 N 为数组长度