2395.和相等的子数组
链接:2395.和相等的子数组
难度:Easy
标签:数组、哈希表
简介:给你一个下标从 0 开始的整数数组 nums ,判断是否存在 两个 长度为 2 的子数组且它们的 和 相等。注意,这两个子数组起始位置的下标必须 不相同 。如果这样的子数组存在,请返回 true,否则返回 false 。
题解 1 - python
- 编辑时间:2023-03-26
- 执行用时:72ms
- 内存消耗:29.8MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
def findSubarrays(self, nums: List[int]) -> bool:
s = set()
for i in range(1, len(nums)):
num = nums[i] + nums[i - 1]
if num in s:
return True
s.add(num)
return False
题解 2 - cpp
- 编辑时间:2023-03-26
- 执行用时:4ms
- 内存消耗:7.6MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
bool findSubarrays(vector<int>& nums) {
unordered_set<int> s;
for (int i = 1; i < nums.size(); i++) {
int num = nums[i] + nums[i - 1];
if (s.count(num)) return true;
s.insert(num);
}
return false;
}
};
题解 3 - rust
- 编辑时间:2023-03-26
- 内存消耗:2.1MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
pub fn find_subarrays(nums: Vec<i32>) -> bool {
let mut s = std::collections::HashSet::<i32>::new();
for i in 1..nums.len() {
let num = nums[i] + nums[i - 1];
if s.contains(&num) {
return true;
}
s.insert(num);
}
false
}
}