Skip to content

Commit

Permalink
Merge pull request soapyigu#368 from soapyigu/Array
Browse files Browse the repository at this point in the history
Array
  • Loading branch information
soapyigu authored Oct 18, 2022
2 parents 35f5dde + e7b7adc commit 096a556
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
50 changes: 50 additions & 0 deletions Array/BombEnemy.swift
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
}
}
29 changes: 29 additions & 0 deletions Array/SquaresSortedArray.swift
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
}
}

0 comments on commit 096a556

Please sign in to comment.