3397
This commit is contained in:
14
include/solution/3397.h
Normal file
14
include/solution/3397.h
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
// This file is generated by mkfile.py
|
||||||
|
// Date: 2025-10-18
|
||||||
|
|
||||||
|
#ifndef INC_3397_H
|
||||||
|
#define INC_3397_H
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C"
|
||||||
|
{
|
||||||
|
#endif
|
||||||
|
int maxDistinctElements(int* nums, int numsSize, int k);
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif // INC_3397_H
|
||||||
41
src/3397.c
Normal file
41
src/3397.c
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
// This file is generated by mkfile.py
|
||||||
|
// Date: 2025-10-18
|
||||||
|
|
||||||
|
#include <solution/3397.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
int cmp(const void *a, const void *b)
|
||||||
|
{
|
||||||
|
return *(int *)a - *(int *)b;
|
||||||
|
}
|
||||||
|
|
||||||
|
int maxDistinctElements(int *nums, int numsSize, int k)
|
||||||
|
{
|
||||||
|
if (numsSize == 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
qsort(nums, numsSize, sizeof(int), cmp);
|
||||||
|
int result = 1;
|
||||||
|
int prev = nums[0] - k;
|
||||||
|
|
||||||
|
for (int i = 1; i < numsSize; i++)
|
||||||
|
{
|
||||||
|
int min = nums[i] - k;
|
||||||
|
int max = nums[i] + k;
|
||||||
|
|
||||||
|
if (prev >= min)
|
||||||
|
{
|
||||||
|
if (max <= prev)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
prev += 1;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
prev = min;
|
||||||
|
}
|
||||||
|
result++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
32
tests/test_3397.cpp
Normal file
32
tests/test_3397.cpp
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
// This file is generated by mkfile.py
|
||||||
|
// Date: 2025-10-18
|
||||||
|
|
||||||
|
#include <solution/3397.h>
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
class MaxDistinctElementsTest : public ::testing::Test {
|
||||||
|
protected:
|
||||||
|
void AssertMaxDistinctElements(std::vector<int> nums, int k, int expected) {
|
||||||
|
int* arr = new int[nums.size()];
|
||||||
|
std::copy(nums.begin(), nums.end(), arr);
|
||||||
|
|
||||||
|
int result = maxDistinctElements(arr, nums.size(), k);
|
||||||
|
ASSERT_EQ(result, expected);
|
||||||
|
|
||||||
|
delete[] arr;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 示例 1
|
||||||
|
TEST_F(MaxDistinctElementsTest, Example1) {
|
||||||
|
// 输入:nums = [1,2,2,3,3,4], k = 2
|
||||||
|
// 输出:6
|
||||||
|
AssertMaxDistinctElements({1, 2, 2, 3, 3, 4}, 2, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例 2
|
||||||
|
TEST_F(MaxDistinctElementsTest, Example2) {
|
||||||
|
// 输入:nums = [4,4,4,4], k = 1
|
||||||
|
// 输出:3
|
||||||
|
AssertMaxDistinctElements({4, 4, 4, 4}, 1, 3);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user