Java&C++题解与拓展——leetcode961.在长度2N的数组中找出重复N次的元素【么的新知识】

96 阅读1分钟
每日一题做题记录,参考官方和三叶的题解

题目要求

在这里插入图片描述

思路一:模拟+哈希表

  • 用哈希表(数组)存每个数出现的次数,超过一次立刻返回该数。

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;
    }
}
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(C)O(C)

C++

class Solution {
    int cnts[10010];
public:
    int repeatedNTimes(vector<int>& nums) {
        for(int n : nums)
            if(++cnts[n] > 1)
                return n;
        return -1;
    }
};
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(C)O(C)

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
    }
}
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(C)O(C)

思路二:模拟

  • 设重复数字为xx,即xx在长度2n2n的数组里出现n+1n+1次,说明两个xx之间顶多隔两个数;
  • 遍历判断当前数和之前的三个是否相等,是则直接返回。

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;
    }
}
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(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;
    }
};
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)

Rust

rust的这个数据类型……这个ii似乎是不会为负,在整数范围内循环取,所以要判定它别太大,来确保数组不越界……

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
    }
}
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)

总结

久违的模拟题~

简单题惯例xiao一下Rust


欢迎指正与讨论!