1051. Height Checker 發表於 2023-02-13 | 分類於 leetcode problemsolutionoption 1 - sorting123456789101112class Solution {public: int heightChecker(vector<int>& heights) { vector<int> expected = heights; sort(expected.begin(),expected.end()); int count =0, n= expected.size(); for(int i=0;i<n;++i){ if(expected[i]!=heights[i]) count++; } return count; }}; option 2 - counting sorted12345678910111213141516class Solution {public: int heightChecker(vector<int>& heights) { vector<int> count(101, 0); for(int h:heights) count[h]++; int ret = 0, i=1, n=heights.size(); for(int j = 0;j<n;++j){ while(count[i]==0) i++; if(i!= heights[j]) ret++; count[i]--; } return ret; }}; analysis time complexity O(nlogn) space complexity O(n)