這是小川的第390次更新,第420篇原創
01 看題和準備
今天介紹的是LeetCode算法題中Easy級別的第252題(順位題號是1051)。要求學生按身高遞增的順序站列來拍年度照片。
返回沒有站在正確位置的學生人數。(這是必須移動的學生人數,以便所有學生身高能夠以遞增的順序排列。)
例如:
輸入:[1,1,4,2,1,3]
輸出:3
說明:身高4,3和最後身高1的學生沒有站在正確的位置。
注意:
1 <= heights.length <= 100
1 <= heights[i] <= 100
02 第一種解法
題目很簡單,找出沒有按高度增序站的學生人數即可。
思路:將原數組的值複製一份出來,將其排序,使用Arrays
類的sort
方法完成,再與原數組對應位置的元素比較,值不相等就加1,最後返回總人數。
時間複雜度爲O(N log(N))
,空間複雜度爲O(N)
。
public int heightChecker(int[] heights) {
int count = 0, n = heights.length;
int[] copy = Arrays.copyOf(heights, n);
Arrays.sort(copy);
for (int i=0; i<n; i++) {
if (heights[i] != copy[i]) {
count++;
}
}
return count;
}
03 第二種解法
還記得前幾天詳細介紹過的計數排序嗎?此題就可以用上,此解法是簡單版實現。
時間複雜度爲O(N)
,空間複雜度爲O(N)
。
public int heightChecker2(int[] heights) {
int[] count = new int[101];
for (int num : heights) {
count[num]++;
}
int n = heights.length, index = 0;
int[] result = new int[n];
for (int i=0; i<count.length; i++) {
while (count[i] > 0) {
result[index++] = i;
count[i]--;
}
}
int times = 0;
for (int i=0; i<n; i++) {
if (heights[i] != result[i]) {
times++;
}
}
return times;
}
04 第三種解法
進階版的計數排序算法實現。
時間複雜度爲O(N)
,空間複雜度爲O(N)
。
public int heightChecker3(int[] heights) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int num : heights) {
min = Math.min(min, num);
max = Math.max(num, max);
}
int[] count = new int[max-min+1+1];
for (int num : heights) {
count[num-min+1]++;
}
for (int i=1; i<count.length; i++) {
count[i] += count[i-1];
}
int n = heights.length;
int[] result = new int[n];
for (int j=0; j<n; j++) {
result[count[heights[j]-min]++] = heights[j];
}
int times = 0;
for (int i=0; i<n; i++) {
if (heights[i] != result[i]) {
times++;
}
}
return times;
}
05 第四種解法
針對簡版的計數排序算法,我們還可以再簡化下,在將排序後的元素填充到新數組時,順便與原數組的對應元素進行比較,省掉後面單獨再開一個for
循環來比較。
時間複雜度爲O(N)
,空間複雜度爲O(N)
。
public int heightChecker4(int[] heights) {
int[] count = new int[101];
for (int num : heights) {
count[num]++;
}
int n = heights.length, index = 0;
int times = 0;
int[] result = new int[n];
for (int i=0; i<count.length; i++) {
while (count[i] > 0) {
result[index] = i;
if (heights[index] != result[index]) {
times++;
}
index++;
count[i]--;
}
}
return times;
}
06 小結
算法專題目前已連續日更超過七個月,算法題文章258+篇,公衆號對話框回覆【數據結構與算法】、【算法】、【數據結構】中的任一關鍵詞,獲取系列文章合集。
以上就是全部內容,如果大家有什麼好的解法思路、建議或者其他問題,可以下方留言交流,點贊、留言、轉發就是對我最大的回報和支持!