-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdestroy-sequential-targets.cpp
More file actions
55 lines (44 loc) · 1.45 KB
/
destroy-sequential-targets.cpp
File metadata and controls
55 lines (44 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
// Created by darion.yaphet on 2025/4/21.
//
#include <vector>
#include <iostream>
#include <unordered_map>
using namespace std;
// https://leetcode.cn/problems/destroy-sequential-targets/
class Solution {
public:
int destroyTargets(vector<int>& nums, int space) {
// 哈希表 count[remainder] 表示模 space 的余数 remainder 出现的次数
unordered_map<int, int> count;
// 哈希表 first[remainder] 表示模 space 的余数 remainder 对应的最小 nums[i]
unordered_map<int, int> first;
for (int num : nums) {
int remainder = num % space;
// 更新 count 和 first
count[remainder]++;
if (first.find(remainder) == first.end() || num < first[remainder]) {
first[remainder] = num;
}
}
// 找到出现次数最多的余数,并记录对应的最小 nums[i]
int maxCount = 0, result = INT32_MAX;
for (const auto& [remainder, cnt] : count) {
if (cnt > maxCount) {
maxCount = cnt;
result = first[remainder];
} else if (cnt == maxCount) {
result = min(result, first[remainder]);
}
}
return result;
}
};
// 测试代码
int main() {
Solution solution;
vector<int> nums = {6, 2, 5};
int space = 10;
cout << "Optimal nums[i]: " << solution.destroyTargets(nums, space) << endl;
return 0;
}