File tree 2 files changed +22
-22
lines changed
2 files changed +22
-22
lines changed Original file line number Diff line number Diff line change 5
5
*/
6
6
7
7
class MaximumSizeSubarraySumEqualsK {
8
- func maxSubArrayLen( nums: [ Int ] , _ k: Int ) -> Int {
9
- var longestLen = 0
10
- var dict = [ Int: Int] ( )
11
- dict [ 0 ] = - 1
12
- var sum = 0
8
+ func maxSubArrayLen( _ nums: [ Int ] , _ k: Int ) -> Int {
9
+ var longestLen = 0 , sum = 0
10
+ var sumToIdx = [ Int: Int] ( )
11
+ sumToIdx [ 0 ] = - 1
13
12
14
- for i in 0 ..< nums. count {
15
- sum += nums [ i ]
13
+ for (i , num ) in nums. enumerated ( ) {
14
+ sum += num
16
15
17
- if let lastIndex = dict [ sum - k] {
18
- longestLen = max ( longestLen, i - lastIndex )
16
+ if let idx = sumToIdx [ sum - k] {
17
+ longestLen = max ( longestLen, i - idx )
19
18
}
20
19
21
- guard let index = dict [ sum] else {
22
- dict [ sum] = i
20
+ guard let idx = sumToIdx [ sum] else {
21
+ sumToIdx [ sum] = i
23
22
continue
24
23
}
25
24
}
Original file line number Diff line number Diff line change 1
1
/**
2
2
* Question Link: https://leetcode.com/problems/move-zeroes/
3
- * Primary idea: keep index zeroIndex, traverse through the array and swap the value
3
+ * Primary idea: keep index for element not equal to 0, traverse and set up the index
4
4
*
5
5
* Time Complexity: O(n), Space Complexity: O(1)
6
6
*
7
7
*/
8
8
9
9
class MoveZeroes {
10
10
func moveZeroes( _ nums: inout [ Int ] ) {
11
- var zeroIndex = 0
12
-
13
- for i in 0 ..< nums. count {
14
- if nums [ i ] != 0 {
15
- _swap ( & nums, i , zeroIndex )
16
- zeroIndex += 1
11
+ var idx = 0
12
+
13
+ for (i , num ) in nums. enumerated ( ) {
14
+ if num != 0 {
15
+ nums [ idx ] = num
16
+ idx += 1
17
17
}
18
18
}
19
- }
20
-
21
- private func _swap< T> ( _ nums: inout Array < T > , _ p: Int , _ q: Int ) {
22
- ( nums [ p] , nums [ q] ) = ( nums [ q] , nums [ p] )
19
+
20
+ while idx < nums. count {
21
+ nums [ idx] = 0
22
+ idx += 1
23
+ }
23
24
}
24
25
}
You can’t perform that action at this time.
0 commit comments