-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix indentation, compilation about trivial missing include, add tests.
- Loading branch information
Showing
1 changed file
with
45 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,46 @@ | ||
/* | ||
Given an integer array and an integer k, return true if the arary has a | ||
(continuous) subarray with length at least two whose elements of the subarray | ||
is a multiple of k. | ||
*/ | ||
#include <vector> | ||
|
||
bool checkSubarraySum(vector<int>& nums, int k) { | ||
const int n = static_cast<int>(nums.size()); | ||
if (n < 2) return false; | ||
int i = 0, j = 1; | ||
unsigned sum = 0; | ||
while (i < n) { | ||
sum += nums[i]; | ||
while (j < n) { | ||
sum += nums[j]; | ||
if (!(sum % k)) return true; | ||
j ++; | ||
} | ||
j--; | ||
sum -= nums[i]; | ||
i++; | ||
if (i == n) break; | ||
while (j >= i + 1) { | ||
if (!(sum % k)) return true; | ||
sum -= nums[j]; | ||
j--; | ||
} | ||
sum -= nums[i]; | ||
i++, j +=2; | ||
} | ||
return false; | ||
} | ||
#include <gtest/gtest.h> | ||
|
||
// Check if the arary has a (continuous) subarray of at least | ||
// two elements whose sum is a multiple of k. | ||
bool check_subarray_sum(const std::vector<int>& nums, int k) | ||
{ | ||
const int n = static_cast<int>(nums.size()); | ||
if (n < 2) return false; | ||
int i = 0, j = 1; | ||
unsigned sum = 0; | ||
while (i < n) { | ||
sum += nums[i]; | ||
while (j < n) { | ||
sum += nums[j]; | ||
if (!(sum % k)) return true; | ||
j ++; | ||
} | ||
j--; | ||
sum -= nums[i]; | ||
i++; | ||
if (i == n) break; | ||
while (j >= i + 1) { | ||
if (!(sum % k)) return true; | ||
sum -= nums[j]; | ||
j--; | ||
} | ||
sum -= nums[i]; | ||
i++, j +=2; | ||
} | ||
return false; | ||
} | ||
|
||
TEST(CheckSubarraySumDivisibility, a) | ||
{ | ||
const std::vector nums{23, 2, 6, 4, 7}; | ||
EXPECT_EQ(check_subarray_sum(nums, 6), true); | ||
EXPECT_EQ(check_subarray_sum(nums, 13), false); | ||
} | ||
|
||
int main(int argc, char **argv) | ||
{ | ||
testing::InitGoogleTest(&argc, argv); | ||
return RUN_ALL_TESTS(); | ||
} |