Leetcode 2598. Smallest Missing Non-negative Integer After Opera
You are given a 0-indexed integer array nums
and an integer value
.
In one operation, you can add or subtract value
from any element of nums
.
For example,
if
nums = [1,2,3]
andvalue = 2
,you can choose to subtract
value
fromnums[0]
to makenums = [-1,2,3]
.
The MEX (minimum excluded) of an array is the smallest missing non-negative integer in it.
For example, the MEX of
[-1,2,3]
is0
while the MEX of[1,0,3]
is2
.
Return the maximum MEX of nums
after applying the mentioned operation any number of times.
Example 1:
Input: nums = [1,-10,7,13,6,8],
value = 5
Output: 4
Explanation: One can achieve this result by applying the following operations:
- Add value to nums[1] twice to make nums = [1,0,7,13,6,8]
- Subtract value from nums[2] once to make nums = [1,0,2,13,6,8]
- Subtract value from nums[3] twice to make nums = [1,0,2,3,6,8]
The MEX of nums is 4. It can be shown that 4 is the maximum MEX
we can achieve.
Example 2:
Input: nums = [1,-10,7,13,6,8], value = 7
Output: 2
Explanation: One can achieve this result by applying the following operation:
- subtract value from nums[2] once to make nums = [1,-10,0,13,6,8]
The MEX of nums is 2. It can be shown that 2 is the maximum MEX
we can achieve.
Constraints:
1 <= nums.length, value <= 105
-109 <= nums[i] <= 109
一直没思路,然后看了lee的思路,但是没看代码,于是自己就按照思路,写出了代码,居然100%,难以置信,方法如下:
A 将所有的数字都对value求余,如果是负数,则求余后,+value 然后再求余,这样保证所有的数字都是正数
B 将所有的数字放到hashmap中,计算每个数字出现的次数,然后按照次数就行排序,
C最后返回的结果一定是次数最少的那个乘以value加上对应的余数。。
好废脑子啊。。。
Runtime: 72 ms, faster than 100.00% of Java online submissions for Smallest Missing Non-negative Integer After Operations.
Memory Usage: 61.8 MB, less than 100.00% of Java online submissions for Smallest Missing Non-negative Integer After Operations.