Given a 0-indexed integer array nums, determine whether there exist
two subarrays of length 2 with equal sum. Note that the two subarrays must begin at different indices.
Return trueif these subarrays exist, andfalseotherwise.
A subarray is a contiguous non-empty sequence of elements within an array.
Input: nums =[0,0,0] Output:true Explanation: The subarrays [nums[0],nums[1]] and [nums[1],nums[2]] have the same sum of 0. Note that even though the subarrays have the same content, the two subarrays are considered different because they are in different positions in the original array.
classSolution {
publicbooleanfindSubarrays(int[] nums) {
Set<Integer> seen =new HashSet<>();
for (int i = 0; i + 1 < nums.length; i++) {
int s = nums[i]+ nums[i+1];
if (seen.contains(s)) returntrue;
seen.add(s);
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funfindSubarrays(nums: IntArray): Boolean {
val seen = mutableSetOf<Int>()
for (i in0 until nums.size-1) {
val s = nums[i] + nums[i+1]
if (s in seen) returntrue seen.add(s)
}
returnfalse }
}
1
2
3
4
5
6
7
8
9
classSolution:
deffindSubarrays(self, nums: list[int]) -> bool:
seen = set()
for i in range(len(nums)-1):
s = nums[i] + nums[i+1]
if s in seen:
returnTrue seen.add(s)
returnFalse
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnfind_subarrays(nums: Vec<i32>) -> bool {
use std::collections::HashSet;
letmut seen = HashSet::new();
for i in0..nums.len()-1 {
let s = nums[i] + nums[i+1];
if!seen.insert(s) {
returntrue;
}
}
false }
}