1051. Height Checker

2019-10-22  本文已影响0人  守住这块热土

1. 题目链接:

https://leetcode.com/problems/height-checker/

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

2. 题目关键词


3. 解题思路

non-decreasing order===》递增顺序。统计待匹配的数组,与排好序数组的各元素是否相等(相等,就说明顺序一致),并统计不相等元素的个数。

class Solution {
public:
    int heightChecker(vector<int>& heights) {
        // 1. copy heights
        vector<int>obj(heights);
        
        // 2. 排序
        sort(obj.begin(),obj.end());//从小到大
        
        int num = 0;
        for(int i = 0; i < obj.size(); i++) {
            if (obj[i] != heights[i]) {
               num++;
            }
        }
        
        return num;
    }
};
上一篇下一篇

猜你喜欢

热点阅读