You are given a 0-indexed array nums
consisting of positive integers, representing targets on a number line. You are also given an integer space
.
You have a machine which can destroy targets. Seeding the machine with some nums[i]
allows it to destroy all targets with values that can be represented as nums[i] + c * space
, where c
is any non-negative integer. You want to destroy the maximum number of targets in nums
.
Return the minimum value of nums[i]
you can seed the machine with to destroy the maximum number of targets.
Example 1:
Input: nums = [3,7,8,1,1,5], space = 2 Output: 1 Explanation: If we seed the machine with nums[3], then we destroy all targets equal to 1,3,5,7,9,... In this case, we would destroy 5 total targets (all except for nums[2]). It is impossible to destroy more than 5 targets, so we return nums[3].
Example 2:
Input: nums = [1,3,5,2,4,6], space = 2 Output: 1 Explanation: Seeding the machine with nums[0], or nums[3] destroys 3 targets. It is not possible to destroy more than 3 targets. Since nums[0] is the minimal integer that can destroy 3 targets, we return 1.
Example 3:
Input: nums = [6,2,5], space = 100 Output: 2 Explanation: Whatever initial seed we select, we can only destroy 1 target. The minimal seed is nums[1].
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= space <= 109
摧毁一系列目标。
给你一个下标从 0 开始的数组 nums ,它包含若干正整数,表示数轴上你需要摧毁的目标所在的位置。同时给你一个整数 space 。
你有一台机器可以摧毁目标。给机器 输入 nums[i] ,这台机器会摧毁所有位置在 nums[i] + c * space 的目标,其中 c 是任意非负整数。你想摧毁 nums 中 尽可能多 的目标。
请你返回在摧毁数目最多的前提下,nums[i] 的 最小值 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/destroy-sequential-targets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是 hashmap + counting sort。按照题意,对于任何一个数字 nums[i],他能够摧毁的目标值满足 nums[i] + c * space,其中 c 是正整数。那么其实所有可以被 nums[i] 摧毁的数字 X 都满足 X % space = nums[i]。发现这个规律之后,我们就可以遍历一遍 input 数组,把数组中的每个数字都 % space,然后以 nums[i] % space 为 key 存入 hashmap。
此时我们再次遍历 input 数组,对于每个数字 num,我们找到他(num % space)在 hashmap 里的对应的 value,这个 value 就是如果以当前数字 nums[i] 作为“武器”,能摧毁的目标数量。我们遍历整个数组,看看哪个武器能摧毁最多的目标,同时注意如果有多个武器摧毁的目标数量一样,取元素值最小的那个。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int destroyTargets(int[] nums, int space) { 3 HashMap<Integer, Integer> map = new HashMap<>(); 4 for (int num : nums) { 5 int key = num % space; 6 map.put(key, map.getOrDefault(key, 0) + 1); 7 } 8 9 int max = 0; 10 int res = 0; 11 for (int num : nums) { 12 int value = map.get(num % space); 13 if (value == max) { 14 res = Math.min(res, num); 15 } else if (value > max) { 16 res = num; 17 max = value; 18 } 19 } 20 return res; 21 } 22 }
相关题目
1010. Pairs of Songs With Total Durations Divisible by 60
2453. Destroy Sequential Targets
标签:num,space,int,nums,LeetCode,Sequential,destroy,Destroy,targets From: https://www.cnblogs.com/cnoodle/p/17026486.html