多味的LeetCode --- 面试题39. 数组中出现次数超过一半的数字

前期回顾:

多味的LeetCode — 面试题 17.10. 主要元素


说明:

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

题目来源:
https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/solution/pai-xu-qu-zhong-zhi-by-xin-ru-zhi-shui-33/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值