意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

LeetCode-Single Number II

来源:恒创科技 编辑:恒创科技编辑部
2024-01-25 23:17:59


Description:
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:


LeetCode-Single Number II

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,3,2]
Output: 3

Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99

题意:给定一个数组,包含出现一次和三次的元素,要求找出只出现了一次的元素;

解法一:这道题和Single Number有个相同的解法,就是利用哈希表来存储元素及其出现的次数,最后遍历表,返回只出现了一次的那个键;

class Solution
public int singleNumber(int[] nums) {
Map<Integer, Integer> count = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
}
for (Integer key : count.keySet()) {
if (count.get(key) == 1) {
return key;
}
}
throw new IllegalArgumentException("No such solution");
}
}

解法二:题目告诉我们只有一个元素仅出现一次,其他元素都出现三次,那么我们可以将数组中所有不相同的元素现相加(即相同的元素只加一次)的三倍,再减去数组中的所有元素的和,得到的应该是只出现一次的那个元素的两倍,最后返回相减的结果的一半就是只出现了一次的那个元素了;这里我们需要使用double类型来存储和,否则会发生溢出;

class Solution {
public int singleNumber(int[] nums) {
double difSum = 0L;
double noDifSum = 0L;
Set<Integer> table = new HashSet<>();
for (int num : nums) {
if (!table.contains(num)) {
table.add(num);
difSum += num;
}
noDifSum += num;
}
return (int)((difSum * 3 - noDifSum) / 2);
}
}


上一篇: LeetCode-Most Common Word 下一篇: 手机怎么远程登录云服务器?