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.
1#include <stdio.h>
2#include <stdlib.h>
3
4int cmp(const void *a, const void *b) {
5 int *row1 = *(int**)a;
6 int *row2 = *(int**)b;
7 return (row1[0] != row2[0]) ? row1[0] - row2[0] : row1[1] - row2[1];
8}
9
10int* kWeakestRows(int** mat, int matSize, int* matColSize, int k, int* returnSize) {
11 int **rowStrength = (int **)malloc(matSize * sizeof(int*));
12 for (int i = 0; i < matSize; ++i) {
13 int count = 0;
14 while (count < *matColSize && mat[i][count] == 1)
15 count++;
16 rowStrength[i] = (int *)malloc(2 * sizeof(int));
17 rowStrength[i][0] = count; // number of soldiers (1s)
18 rowStrength[i][1] = i; // row index
19 }
20 qsort(rowStrength, matSize, sizeof(rowStrength[0]), cmp);
21 int *weakestRows = (int *)malloc(k * sizeof(int));
22 for (int i = 0; i < k; ++i)
23 weakestRows[i] = rowStrength[i][1];
24 for (int i = 0; i < matSize; ++i)
25 free(rowStrength[i]);
26 free(rowStrength);
27 *returnSize = k;
28 return weakestRows;
29}
The C solution involves using a two-dimensional array to track the number of soldiers and their respective row indices. We then use the quicksort function with a custom comparator to sort this array by soldiers' count first and indices as a tiebreaker. Finally, extract the indices of the weakest rows.
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.