前期回顾:
说明:
leetcode上的该题不需要考虑数组中不满足条件的情况,而剑指offer中需要考虑这个情况。因此,本博客在接下来的解析中会出现return 0 或者不考虑return 0的情况。
题目描述:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
解题思路1:
使用Counter,注意元组的读取方式
代码1:
写法1:
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
if not numbers: return 0
count = Counter(numbers).most_common() # [(2, 5), (1, 1), (3, 1), (5, 1), (4, 1)]
if count[0][1] > len(numbers) / 2:
return count[0][0]
return 0
s = Solution()
numbers = [1,2,3,2,2,2,5,4,2]
print(s.MoreThanHalfNum_Solution(numbers))
写法2:
from collections import Counter
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
if numbers is None: return 0
count = list(Counter(numbers).items())
for item in count:
if item[1] > len(numbers) // 2:
return item[0]
return 0
写法3:
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
from collections import Counter
if numbers is None:
return 0
index = len(numbers) // 2
for i in set(numbers): # set的功能是去掉重复数字
if Counter(numbers)[i] > index: # 这里的Counter是通过键来访问值的方式
return i
return 0
解题思路2:
已知数组中一定存在出现次数超过数组长度一半的数字,那么排序后该数字一定是中位数
代码2:
python版:
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
if not numbers: return 0
count = sorted(numbers)
return count[len(numbers)//2]
s = Solution()
numbers = [1,2,3,2,2,2,5,4,2]
print(s.MoreThanHalfNum_Solution(numbers))
java版:
import java.util.Arrays;
public class Solution {
private int count(int x,int[] array) {
// TODO 自动生成的方法存根
int num=0;
for (int i = 0; i < array.length; i++) {
if(x==array[i])
num++;
}
return num;
}
public int MoreThanHalfNum_Solution(int [] array) {
int num=0;
for (int i = 0; i < array.length; i++) {
if(count(array[i], array)>array.length/2){
num=array[i];
}
}
return num;
}
}
不能全部运行通过:例如[1,2,3,2,4,2,5,2,3]
import java.util.Arrays;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int num = 0;
Arrays.sort(array);
if(array.length/2 > 0){
return array[array.length/2];
}
return num;
}
}