Easy
题目描述
给你一个整数数组 nums。
返回数组中第一个(按数组索引最早出现)恰好出现一次的偶数。如果不存在这样的整数,返回 -1。
如果一个整数 x 能被 2 整除,则认为它是偶数。
示例 1:
输入:nums = [3,4,2,5,4,6]
输出:2
解释:
2 和 6 都是偶数且恰好出现一次。由于 2 在数组中首先出现,所以答案是 2。
示例 2:
输入:nums = [4,4]
输出:-1
解释:
没有偶数恰好出现一次,所以返回 -1。
提示:
1 <= nums.length <= 1001 <= nums[i] <= 100
解题思路
这道题要求找到第一个恰好出现一次的偶数元素。我们可以用哈希表来解决这个问题。
思路分析
方法一:两次遍历(推荐)
- 第一次遍历:统计所有偶数元素的出现次数
- 第二次遍历:按原数组顺序找到第一个出现次数为1的偶数
这种方法的优点是思路清晰,代码简洁,时间复杂度为O(n)。
方法二:一次遍历 + 标记 使用哈希表记录每个偶数的状态:未出现、出现一次、出现多次。一边遍历一边更新状态,最后再遍历数组找第一个状态为"出现一次"的偶数。
方法三:暴力解法 对每个偶数元素,遍历整个数组统计其出现次数。时间复杂度为O(n²),不推荐。
由于数组长度最大为100,所有方法的性能差异不大,但方法一代码最简洁易懂。
代码实现
class Solution {
public:
int firstUniqueEven(vector<int>& nums) {
unordered_map<int, int> count;
// 统计所有偶数的出现次数
for (int num : nums) {
if (num % 2 == 0) {
count[num]++;
}
}
// 找到第一个出现次数为1的偶数
for (int num : nums) {
if (num % 2 == 0 && count[num] == 1) {
return num;
}
}
return -1;
}
};
class Solution:
def firstUniqueEven(self, nums: list[int]) -> int:
count = {}
# 统计所有偶数的出现次数
for num in nums:
if num % 2 == 0:
count[num] = count.get(num, 0) + 1
# 找到第一个出现次数为1的偶数
for num in nums:
if num % 2 == 0 and count[num] == 1:
return num
return -1
public class Solution {
public int FirstUniqueEven(int[] nums) {
var count = new Dictionary<int, int>();
// 统计所有偶数的出现次数
foreach (int num in nums) {
if (num % 2 == 0) {
count[num] = count.ContainsKey(num) ? count[num] + 1 : 1;
}
}
// 找到第一个出现次数为1的偶数
foreach (int num in nums) {
if (num % 2 == 0 && count[num] == 1) {
return num;
}
}
return -1;
}
}
/**
* @param {number[]} nums
* @return {number}
*/
var firstUniqueEven = function(nums) {
const count = {};
for (let num of nums) {
count[num] = (count[num] || 0) + 1;
}
for (let num of nums) {
if (num % 2 === 0 && count[num] === 1) {
return num;
}
}
return -1;
};
复杂度分析
| 复杂度 | 分析 |
|---|---|
| 时间复杂度 | O(n),其中 n 是数组长度。需要遍历数组两次 |
| 空间复杂度 | O(k),其中 k 是不同偶数的个数,最坏情况下为 O(n) |