Skip to content

2453. Destroy Sequential Targets 👍

Approach 1: Hash Map

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int destroyTargets(vector<int>& nums, int space) {
    int ans = INT_MAX;
    int maxCount = 0;
    unordered_map<int, int> count;

    for (const int num : nums)
      maxCount = max(maxCount, ++count[num % space]);

    for (const int num : nums)
      if (count[num % space] == maxCount)
        ans = min(ans, num);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int destroyTargets(int[] nums, int space) {
    int ans = Integer.MAX_VALUE;
    int maxCount = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (final int num : nums) {
      count.merge(num % space, 1, Integer::sum);
      maxCount = Math.max(maxCount, count.get(num % space));
    }

    for (final int num : nums)
      if (count.get(num % space) == maxCount)
        ans = Math.min(ans, num);

    return ans;
  }
}
1
2
3
4
5
class Solution:
  def destroyTargets(self, nums: List[int], space: int) -> int:
    count = collections.Counter([num % space for num in nums])
    maxCount = max(count.values())
    return min(num for num in nums if count[num % space] == maxCount)

Approach 2: C++ std::max_element

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int destroyTargets(vector<int>& nums, int space) {
    unordered_map<int, int> count;

    for (const int num : nums)
      ++count[num % space];

    return *max_element(begin(nums), end(nums), [&count, space](int a, int b) {
      const int countA = count[a % space];
      const int countB = count[b % space];
      return countA == countB ? a > b : countA < countB;
    });
  }
};