我们只需要对数组进行一次遍历。当我们遍历到第 i 个元素时,计算 nums}[i] + \textit{nums}[i + 1] 的值,并判断该值是否已经出现过即可。
判断的操作可以使用一个哈希表,记录已经出现过的值。
代码
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: boolfindSubarrays(vector<int>& nums){ int n = nums.size(); unordered_set<int> seen; for (int i = 0; i < n - 1; ++i) { int sum = nums[i] + nums[i + 1]; if (seen.count(sum)) { returntrue; } seen.insert(sum); } returnfalse; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { publicbooleanfindSubarrays(int[] nums) { intn= nums.length; Set<Integer> seen = newHashSet<Integer>(); for (inti=0; i < n - 1; ++i) { intsum= nums[i] + nums[i + 1]; if (!seen.add(sum)) { returntrue; } } returnfalse; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassSolution { publicboolFindSubarrays(int[] nums) { int n = nums.Length; ISet<int> seen = new HashSet<int>(); for (int i = 0; i < n - 1; ++i) { int sum = nums[i] + nums[i + 1]; if (!seen.Add(sum)) { returntrue; } } returnfalse; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10
classSolution: deffindSubarrays(self, nums: List[int]) -> bool: n = len(nums) seen = set() for i inrange(n - 1): total = nums[i] + nums[i + 1] if total in seen: returnTrue seen.add(total) returnFalse
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12
var findSubarrays = function(nums) { const n = nums.length; const seen = newSet(); for (let i = 0; i < n - 1; ++i) { let sum = nums[i] + nums[i + 1]; if (seen.has(sum)) { returntrue; } seen.add(sum); } returnfalse; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11
funcfindSubarrays(nums []int)bool { seen := map[int]bool{} for i := 1; i < len(nums); i++ { sum := nums[i-1] + nums[i] if seen[sum] { returntrue } seen[sum] = true } returnfalse }