forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request soapyigu#368 from soapyigu/Array
Array
- Loading branch information
Showing
2 changed files
with
79 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/bomb-enemy/ | ||
* Primary idea: Greedy. Update the result only when there is wall or at the beginning. | ||
* Time Complexity: O(mn), Space Complexity: O(n) | ||
* | ||
*/ | ||
|
||
class BombEnemy { | ||
func maxKilledEnemies(_ grid: [[Character]]) -> Int { | ||
let m = grid.count, n = grid[0].count | ||
var res = 0, rowHit = 0, colHit = Array(repeating: 0, count: n) | ||
|
||
for i in 0..<m { | ||
for j in 0..<n { | ||
|
||
// check row | ||
if j == 0 || grid[i][j - 1] == "W" { | ||
rowHit = 0 | ||
for y in j..<n { | ||
if grid[i][y] == "W" { | ||
break | ||
} | ||
if grid[i][y] == "E" { | ||
rowHit += 1 | ||
} | ||
} | ||
} | ||
|
||
// check col | ||
if i == 0 || grid[i - 1][j] == "W" { | ||
colHit[j] = 0 | ||
for x in i..<m { | ||
if grid[x][j] == "W" { | ||
break | ||
} | ||
if grid[x][j] == "E" { | ||
colHit[j] += 1 | ||
} | ||
} | ||
} | ||
|
||
if grid[i][j] == "0" { | ||
res = max(res, rowHit + colHit[j]) | ||
} | ||
} | ||
} | ||
|
||
return res | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/squares-of-a-sorted-array/ | ||
* Primary idea: Two pointers. Compare absolute value and assign the bigger one to the right most index of the result. | ||
* Time Complexity: O(n), Space Complexity: O(1) | ||
* | ||
*/ | ||
|
||
class SquaresSortedArray { | ||
func sortedSquares(_ nums: [Int]) -> [Int] { | ||
var left = 0, right = nums.count - 1, res = Array(repeating: 0, count: nums.count) | ||
var square = 0, idx = nums.count - 1 | ||
|
||
while left <= right { | ||
|
||
if abs(nums[left]) < abs(nums[right]) { | ||
square = nums[right] | ||
right -= 1 | ||
} else { | ||
square = nums[left] | ||
left += 1 | ||
} | ||
|
||
res[idx] = square * square | ||
idx -= 1 | ||
} | ||
|
||
return res | ||
} | ||
} |