剑指 Offer 39:数组中出现次数超过一半的数字

This commit is contained in:
huangge1199@hotmail.com 2021-07-17 23:02:23 +08:00
parent 0347cbcb08
commit 8c6aeafc53
2 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,49 @@
//数组中有一个数字出现的次数超过数组长度的一半请找出这个数字
//
//
//
// 你可以假设数组是非空的并且给定的数组总是存在多数元素
//
//
//
// 示例 1:
//
// 输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
//输出: 2
//
//
//
// 限制
//
// 1 <= 数组长度 <= 50000
//
//
//
// 注意本题与主站 169 题相同https://leetcode-cn.com/problems/majority-element/
//
//
// Related Topics 数组 哈希表 分治 计数 排序
// 👍 174 👎 0
package leetcode.editor.cn;
import java.util.Arrays;
//剑指 Offer 39:数组中出现次数超过一半的数字
class ShuZuZhongChuXianCiShuChaoGuoYiBanDeShuZiLcof {
public static void main(String[] args) {
//测试代码
Solution solution = new ShuZuZhongChuXianCiShuChaoGuoYiBanDeShuZiLcof().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,25 @@
<p>数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。</p>
<p>&nbsp;</p>
<p>你可以假设数组是非空的,并且给定的数组总是存在多数元素。</p>
<p>&nbsp;</p>
<p><strong>示例&nbsp;1:</strong></p>
<pre><strong>输入:</strong> [1, 2, 3, 2, 2, 2, 5, 4, 2]
<strong>输出:</strong> 2</pre>
<p>&nbsp;</p>
<p><strong>限制:</strong></p>
<p><code>1 &lt;= 数组长度 &lt;= 50000</code></p>
<p>&nbsp;</p>
<p>注意:本题与主站 169 题相同:<a href="https://leetcode-cn.com/problems/majority-element/">https://leetcode-cn.com/problems/majority-element/</a></p>
<p>&nbsp;</p>
<div><div>Related Topics</div><div><li>数组</li><li>哈希表</li><li>分治</li><li>计数</li><li>排序</li></div></div>\n<div><li>👍 174</li><li>👎 0</li></div>