Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

多数元素——Java版投票算法 #566

Merged
merged 1 commit into from
Sep 25, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 21 additions & 1 deletion problems/169.majority-element.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ https://leetcode-cn.com/problems/majority-element/

## 代码

- 语言支持:JS,Python, CPP
- 语言支持:JS,Python, CPP,Java

Javascript Code:

Expand Down Expand Up @@ -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 为数组长度
Expand Down