Sponsored
Sponsored
In this approach, we directly count the number of soldiers in each row by iterating through the elements of the row, and then sort the rows based on the count followed by their index to determine the order.
Steps to implement:
Time Complexity: O(m*n + m*log m) due to counting and sorting the rows.
Space Complexity: O(m) to store the row strength information.
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int[] KWeakestRows(int[][] mat, int k) {
var rowStrength = new List<Tuple<int, int>>();
for (int i = 0; i < mat.Length; i++) {
int soldierCount = 0;
for (int j = 0; j < mat[i].Length; j++) {
if (mat[i][j] == 1) soldierCount++;
else break;
}
rowStrength.Add(new Tuple<int, int>(soldierCount, i));
}
rowStrength.Sort();
return rowStrength.Take(k).Select(x => x.Item2).ToArray();
}
}
This C# solution utilizes a List of Tuples to store each row’s soldier count and index. The list is sorted using the Default Tuple comparison and indices of the weakest rows are selected using Linq Take function.
This approach uses binary search to efficiently count the number of soldiers in each row. Given that soldiers are always positioned before civilians, binary search can help quickly find the first civilian and thus the count of soldiers.
Implementation steps:
Time Complexity: O(m*log n + m*log m) due to binary search for counting and sorting rows.
Space Complexity: O(m), for maintaining strength array storage.
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public class Solution {
6 private int CountSoldiers(int[] row) {
7 int low = 0, high = row.Length - 1;
8 while (low <= high) {
9 int mid = (low + high) / 2;
10 if (row[mid] == 1)
11 low = mid + 1;
12 else
13 high = mid - 1;
14 }
15 return low;
16 }
17
18 public int[] KWeakestRows(int[][] mat, int k) {
19 var rowStrength = new List<Tuple<int, int>>();
20 for (int i = 0; i < mat.Length; i++) {
21 int soldierCount = CountSoldiers(mat[i]);
22 rowStrength.Add(new Tuple<int, int>(soldierCount, i));
23 }
24 rowStrength.Sort();
25 return rowStrength.Take(k).Select(x => x.Item2).ToArray();
26 }
27}
For C#, the approach of employing a binary search within the Counting of soldiers method mirrors prior techniques, optimizing the evaluation of soldier numbers before results are sorted by traditional List and Tuple operations.