Skip to content

Commit 264d2ab

Browse files
committed
Add a solution to the Frequency of the Most Frequent Element
1 parent c712ca0 commit 264d2ab

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/frequency-of-the-most-frequent-element/
3+
* Primary idea: Slding window, sort the nums and move left if k cannot make current window even.
4+
*
5+
* Time Complexity: O(nlogn), Space Complexity: O(1)
6+
*
7+
*/
8+
9+
class FrequencyMostFrequentElement {
10+
func maxFrequency(_ nums: [Int], _ k: Int) -> Int {
11+
let nums = nums.sorted()
12+
var left = 0, res = 1, sum = 0
13+
14+
for (i, num) in nums.enumerated() {
15+
sum += num
16+
17+
while (i - left + 1) * num - sum > k {
18+
sum -= nums[left]
19+
left += 1
20+
}
21+
22+
res = max(res, i - left + 1)
23+
}
24+
25+
return res
26+
}
27+
}

SlidingWindow/LongestContinuousSubarrayLimit.swift

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* Question Link: https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/description/
2+
* Question Link: https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/
33
* Primary idea: Slding window, use max and min queues to track largest difference along the way. Move left pointer to get the potential result.
44
*
55
* Note: k may be invalid, mention that with interviewer
@@ -9,7 +9,7 @@
99

1010
class LongestContinuousSubarrayLimit {
1111
func longestSubarray(_ nums: [Int], _ limit: Int) -> Int {
12-
var maxQueue = [Int](), minQueue = [Int](), left = 0, size = 0
12+
var maxQueue = [Int](), minQueue = [Int](), left = 0, res = 0
1313

1414
for (i, num) in nums.enumerated() {
1515
while !maxQueue.isEmpty && maxQueue.last! < num {
@@ -33,9 +33,9 @@ class LongestContinuousSubarrayLimit {
3333
left += 1
3434
}
3535

36-
size = max(size, i - left + 1)
36+
res = max(res, i - left + 1)
3737
}
3838

39-
return size
39+
return res
4040
}
41-
}
41+
}

0 commit comments

Comments
 (0)