学堂 学堂 学堂公众号手机端

LeetCode-Single Number II

lewis 1年前 (2024-04-21) 阅读数 17 #技术


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:


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


版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门