Skip to content

Commit 096a556

Browse files
authored
Merge pull request soapyigu#368 from soapyigu/Array
Array
2 parents 35f5dde + e7b7adc commit 096a556

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

Array/BombEnemy.swift

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/bomb-enemy/
3+
* Primary idea: Greedy. Update the result only when there is wall or at the beginning.
4+
* Time Complexity: O(mn), Space Complexity: O(n)
5+
*
6+
*/
7+
8+
class BombEnemy {
9+
func maxKilledEnemies(_ grid: [[Character]]) -> Int {
10+
let m = grid.count, n = grid[0].count
11+
var res = 0, rowHit = 0, colHit = Array(repeating: 0, count: n)
12+
13+
for i in 0..<m {
14+
for j in 0..<n {
15+
16+
// check row
17+
if j == 0 || grid[i][j - 1] == "W" {
18+
rowHit = 0
19+
for y in j..<n {
20+
if grid[i][y] == "W" {
21+
break
22+
}
23+
if grid[i][y] == "E" {
24+
rowHit += 1
25+
}
26+
}
27+
}
28+
29+
// check col
30+
if i == 0 || grid[i - 1][j] == "W" {
31+
colHit[j] = 0
32+
for x in i..<m {
33+
if grid[x][j] == "W" {
34+
break
35+
}
36+
if grid[x][j] == "E" {
37+
colHit[j] += 1
38+
}
39+
}
40+
}
41+
42+
if grid[i][j] == "0" {
43+
res = max(res, rowHit + colHit[j])
44+
}
45+
}
46+
}
47+
48+
return res
49+
}
50+
}

Array/SquaresSortedArray.swift

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/squares-of-a-sorted-array/
3+
* Primary idea: Two pointers. Compare absolute value and assign the bigger one to the right most index of the result.
4+
* Time Complexity: O(n), Space Complexity: O(1)
5+
*
6+
*/
7+
8+
class SquaresSortedArray {
9+
func sortedSquares(_ nums: [Int]) -> [Int] {
10+
var left = 0, right = nums.count - 1, res = Array(repeating: 0, count: nums.count)
11+
var square = 0, idx = nums.count - 1
12+
13+
while left <= right {
14+
15+
if abs(nums[left]) < abs(nums[right]) {
16+
square = nums[right]
17+
right -= 1
18+
} else {
19+
square = nums[left]
20+
left += 1
21+
}
22+
23+
res[idx] = square * square
24+
idx -= 1
25+
}
26+
27+
return res
28+
}
29+
}

0 commit comments

Comments
 (0)