| 每日一题做题记录,参考官方和三叶的题解 |
题目要求
思路一:模拟+哈希表
- 用哈希表(数组)存每个数出现的次数,超过一次立刻返回该数。
Java
class Solution {
int[] cnts = new int[10010];
public int repeatedNTimes(int[] nums) {
for(int n : nums) {
if(++cnts[n] > 1)
return n;
}
return -1;
}
}
- 时间复杂度:
- 空间复杂度:
C++
class Solution {
int cnts[10010];
public:
int repeatedNTimes(vector<int>& nums) {
for(int n : nums)
if(++cnts[n] > 1)
return n;
return -1;
}
};
- 时间复杂度:
- 空间复杂度:
Rust
use std::collections::HashSet;
impl Solution {
pub fn repeated_n_times(nums: Vec<i32>) -> i32 {
let mut cnts = HashSet::new();
for n in nums {
if cnts.contains(&n){
return n;
}
cnts.insert(n);
}
-1
}
}
- 时间复杂度:
- 空间复杂度:
思路二:模拟
- 设重复数字为,即在长度的数组里出现次,说明两个之间顶多隔两个数;
- 遍历判断当前数和之前的三个是否相等,是则直接返回。
Java
class Solution {
public int repeatedNTimes(int[] nums) {
int n = nums.length;
for(int i = 2; i < n; i++) {
int t = nums[i];
if(i - 1 >= 0 && nums[i - 1] == t)
return t;
if(i - 2 >= 0 && nums[i - 2] == t)
return t;
if(i - 3 >= 0 && nums[i - 3] == t)
return t;
}
return -1;
}
}
- 时间复杂度:
- 空间复杂度:
C++
class Solution {
public:
int repeatedNTimes(vector<int>& nums) {
int n = nums.size();
for(int i = 2; i < n; i++) {
int t = nums[i];
if(i - 1 >= 0 && nums[i - 1] == t)
return t;
if(i - 2 >= 0 && nums[i - 2] == t)
return t;
if(i - 3 >= 0 && nums[i - 3] == t)
return t;
}
return -1;
}
};
- 时间复杂度:
- 空间复杂度:
Rust
rust的这个数据类型……这个似乎是不会为负,在整数范围内循环取,所以要判定它别太大,来确保数组不越界……
impl Solution {
pub fn repeated_n_times(nums: Vec<i32>) -> i32 {
let n = nums.len();
for i in (2..n) {
let mut t = nums[i];
if i - 1 >= 0 && i - 1 <= 10010 && nums[i - 1] == t {
return t;
}
if i - 2 >= 0 && i - 2 <= 10010 && nums[i - 2] == t {
return t;
}
if i - 3 >= 0 && i - 3 <= 10010 && nums[i - 3] == t {
return t;
}
}
-1
}
}
- 时间复杂度:
- 空间复杂度:
总结
久违的模拟题~
简单题惯例xiao一下Rust
| 欢迎指正与讨论! |