703311. Tywin's War Strategy
Basic
Tywin's War Strategy
Summary
Tywin's War Strategy is a basic algorithm problem that involves sorting and manipulation of arrays. The problem requires you to sort an array in descending order based on the strength of the army, then in ascending order based on the number of soldiers.
Detailed Explanation
To solve this problem, we will use the following steps:
- First, sort the array in descending order based on the strength of the army.
- Then, sort the array in ascending order based on the number of soldiers.
- Finally, return the sorted array.
Here's a step-by-step breakdown of the solution:
Input: [[10, 5], [8, 4], [7, 6], [9, 3]]
Output: [[10, 5], [9, 3], [8, 4], [7, 6]]
Step 1:
Sort the array in descending order based on the strength of the army.
[[10, 5], [9, 3], [8, 4], [7, 6]]
Sorting:
[[10, 5]], [[9, 3]], [[8, 4]], [[7, 6]]
Step 2:
Sort the array in ascending order based on the number of soldiers.
Sorting:
[[10, 5]], [[9, 3]], [[8, 4]], [[7, 6]]
Final output:
[[10, 5], [9, 3], [8, 4], [7, 6]]
Time complexity: O(n log n) due to the sorting operation. Space complexity: O(1) as we are not using any extra space.
Optimized Solutions
Java
import java.util.Arrays;
public class TywinsWarStrategy {
public static int[][] sortArmies(int[][] armies) {
Arrays.sort(armies, (a, b) -> Integer.compare(b[0], a[0]));
Arrays.sort(armies, (a, b) -> Integer.compare(a[1], b[1]));
return armies;
}
}