|
|
@ -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; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|