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 为数组长度