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.
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public class Solution {
6 public int[] KWeakestRows(int[][] mat, int k) {
7 var rowStrength = new List<Tuple<int, int>>();
8 for (int i = 0; i < mat.Length; i++) {
9 int soldierCount = 0;
10 for (int j = 0; j < mat[i].Length; j++) {
11 if (mat[i][j] == 1) soldierCount++;
12 else break;
13 }
14 rowStrength.Add(new Tuple<int, int>(soldierCount, i));
15 }
16 rowStrength.Sort();
17 return rowStrength.Take(k).Select(x => x.Item2).ToArray();
18 }
19}
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.
This solution optimizes soldier count using binary search in each row. This reduces the time complexity to efficiently find each row's strength before sorting and extracting indices.