Students are asked to stand in non-decreasing order of heights for an annual photo.
Return the minimum number of students not standing in the right positions. (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.)
Example 1:
Input: [1,1,4,2,1,3] Output: 3 Explanation: Students with heights 4, 3 and the last 1 are not standing in the right positions.
Note:
1 <= heights.length <= 100
1 <= heights[i] <= 100
Approach #1 我的解法,Arrays.sort(), Arrays.copyOf()
class Solution {
public int heightChecker(int[] heights) {
int[] unsorted = Arrays.copyOf(heights,heights.length);
int num = 0;
Arrays.sort(heights);
for(int i=0;i<heights.length;i++){
if (unsorted[i]!=heights[i])
num+=1;
}
return num;
}
}
分析
时间复杂度,O(nlog(n))
空间复杂度,O(n)
Approach #2 Counting Sort
class Solution {
public int heightChecker(int[] heights) {
int[] heightToFreq = new int[101];
for (int height : heights) {
heightToFreq[height]++; //calculate the frequency of each height.
}
int result = 0;
int curHeight = 0;
for (int i = 0; i < heights.length; i++) {
while (heightToFreq[curHeight] == 0) { //curHeight增加到剩余的最低身高
curHeight++;
}
if (curHeight != heights[i]) { //如果队伍是完全排序的,curHeight应该
result++; //等于此时的身高
}
heightToFreq[curHeight]--;
}
return result;
}
}
分析:
计数排序
它的优势在于在对一定范围内的整数排序时,它的复杂度为Ο(n+k)(其中k是整数的范围),快于任何比较排序算法。 [1-2] 当然这是一种牺牲空间换取时间的做法,而且当O(k)>O(n*log(n))的时候其效率反而不如基于比较的排序(基于比较的排序的时间复杂度在理论上的下限是O(n*log(n)), 如归并排序,堆排序)。
应用场景: 数据重复出现次数大 数据紧凑。
public class CountSort {
public static void countSort(int[] arr) {
if (arr == null || arr.length == 0)
return;
int max = max(arr); //寻找数组中最大值
int[] count = new int[max + 1]; //建立临时数组, 长度为max+1
Arrays.fill(count, 0); //使用0填充数组中的元素
//使用待排序数组的元素作为临时数组的下标,并且统计每个元素的个数
for (int i = 0; i < arr.length; i++) {
count[arr[i]] = count[arr[i]] + 1;
}
int arrIndex = 0;
for (int i = 0; i <= max; i++) { //从0到max挨个遍历
//遍历临时数组某下标对应的数组元素值,数组元素值代表下标值出现了几次,依次添加到目标数组
for (int j = 0; j < count[i]; j++) {
arr[arrIndex++] = i;
}
}
}
// 寻找数组中最大值的方法
public static int max(int[] arr) {
int max = Integer.MIN_VALUE;
for (int ele : arr) {
if (ele > max)
max = ele;
}
return max;
}
}