LintCode:Majority Number / Majority Number II / Majority Number III

本文探讨了一种在数组中寻找出现次数超过数组长度三分之一的主元素的方法。通过使用HashMap统计每个元素出现的次数来实现,并对比了一种试图通过抵消计数的方法,指出其存在的问题及局限性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天看到LintCode一题:

Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.
Find it.

example:Given [1, 2, 1, 2, 1, 3, 3], return 1.


给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一。

例子:给出数组[1,2,1,2,1,3,3] 返回 1。


我的做法是使用hashmap将数组中的数与键对应,统计个数与值对应。

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: The majority number that occurs more than 1/3
     */
    public int majorityNumber(ArrayList<Integer> nums) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		for (Integer integer : nums) {
			if (map.get(integer) != null) {
				map.put(integer, map.get(integer)+1);
			}else {
				map.put(integer, 1);
			}
		}
		for (Integer integer : map.keySet()) {
			if (map.get(integer) > nums.size()/3) {
				return integer;
			}
		}
		return 0;
    }
}

以上做法对Majority Number / Majority Number II / Majority Number III 这三道题来说都可以用。


我在网上找到一个解决方法如下的:

思路:三三抵销,同时记录剩下的值各自出现的次数,出现次数多的值为答案。

我也将其测试了一下,发现不通过。代码如下:

public int majorityNumber(ArrayList<Integer> nums) {
		int count1 = 0, count2 = 0;
		int flag1 = 0, flag2 = 0;
		int temp = 0;
		for (int i = 0; i < nums.size(); i++) {
			temp = nums.get(i);
			if (count1 == 0) {
				flag1 = temp;
			}
			if (count2 == 0 && temp != flag1) {
				flag2 = temp;
			}
			if (temp != flag1 && temp != flag2 && count1 != 0 && count2 != 0) {
				count1--;
				count2--;
			}
			if (temp == flag1) {
				count1++;
			}
			if (temp == flag2) {
				count2++;
			}
		}
		return count1 > count2 ? flag1 : flag2;
	}

不能通过后,我看了一下,是抵消会出问题。会存在这样一种情况,假如有3*n+1个数,当恰好前面的3*n个抵消了,多出来的1个就会被当做主元素,其实第3*n+1个不一定是主元素。(3*n+2个数也是这样)

举例说明:

[1,2,3,4] 这时count1=1,count2=,0,所以返回4。

[1,2,3,4,5] 这个时候count1=count2=1,所以返回5。

在这两种情况下都是没解的。


不知道是我认识不够,还是什么原因。我在网上看了几篇文章,用这种方法,竟然通过测试了。小伙伴们看到这里的话,如果知道怎么解释或者解决这个问题的话,麻烦给我解释一下。谢谢了!

### 关于 `ValueError` 的原因分析 当尝试将字符串 `'Late Majority'` 转换为浮点数时,Python 抛出了 `ValueError: could not convert string to float: 'Late Majority'`。这是因为 Python 的内置函数 `float()` 只能处理表示数值的字符串(例如 `'123.45'` 或 `'0.789'`),而无法解析包含字母或其他非数字字符的字符串[^1]。 --- ### 解决方案 #### 方法一:数据预处理 如果输入的数据可能包含非数字字符,则需要先对其进行清理。可以使用正则表达式提取其中的数字部分: ```python import re def extract_float_from_string(s): try: # 使用正则表达式匹配字符串中的所有数字 numbers = re.findall(r"[-+]?\d*\.\d+|\d+", s) if numbers: return float(numbers[0]) # 将第一个找到的数字转换为浮点数 else: raise ValueError(f"No numeric value found in '{s}'") except Exception as e: print(e) result = extract_float_from_string('Late Majority') print(result) # 如果无有效数字会抛出异常并打印错误消息 ``` 上述方法通过正则表达式查找字符串中的任何合法浮点数形式,并将其转换为实际的浮点数值。 --- #### 方法二:验证输入合法性 在执行类型转换之前,可以通过条件判断来确认字符串是否可被成功转换为浮点数。这有助于提前捕获潜在问题: ```python def is_convertible_to_float(value): try: float(value) return True except ValueError: return False input_str = 'Late Majority' if is_convertible_to_float(input_str): result = float(input_str) else: print(f"'{input_str}' cannot be converted into a floating-point number.") ``` 此实现方式提供了一种简单的机制用于测试给定值能否安全地转变为所需的浮点型变量。 --- #### 方法三:自定义异常处理逻辑 对于那些确实应该作为特定业务场景下的特殊标记而非真正意义上的数量级单位存在的标签类文字内容(比如这里的 "Late Majority"),我们应当设计专门针对这种情况作出响应而不是单纯依赖标准库的行为模式。下面展示了一个例子,在遇到不可转译的情况返回默认值或者触发其他动作路径: ```python DEFAULT_FLOAT_VALUE = 0.0 def safe_cast_to_float(text, default=DEFAULT_FLOAT_VALUE): """Safely attempts conversion from str -> float.""" try: return float(text.strip()) except (TypeError, ValueError): return default example_input = 'Late Majority' converted_value = safe_cast_to_float(example_input) print(converted_value) # 输出将是预先设定好的缺省值,默认情况下即零。 ``` 这里采用了更稳健的设计理念——即使面对完全不合规格的数据源也能够保持程序运行流畅而不崩溃中断服务流程. --- ### 总结说明 以上三种策略分别适用于不同情境下解决因非法字符引发的 `ValueError` 错误状况。具体采用哪一种取决于应用背景以及需求优先级等因素考量之后再做决定最为合适不过了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值