diff --git a/blogs/Algorithm/剑指 Offer/数组相关.md b/blogs/Algorithm/剑指 Offer/数组相关.md index 7883f54..1dc8f9f 100644 --- a/blogs/Algorithm/剑指 Offer/数组相关.md +++ b/blogs/Algorithm/剑指 Offer/数组相关.md @@ -96,3 +96,31 @@ class Solution { } ``` +[39. 数组中出现次数超过一半的数字](https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/) + +```java +class Solution { + + public int majorityElement(int[] nums) { + Arrays.sort(nums); + return nums[nums.length / 2]; + } +} +``` + +```java +class Solution { + + public int majorityElement(int[] nums) { + int count = 0, result = 0; + for (int num : nums) { + if (count == 0) { + result = num; + } + count += (result == num) ? 1 : -1; + } + return result; + } +} +``` +