美文网首页
1051. Height Checker

1051. Height Checker

作者: 守住这块热土 | 来源:发表于2019-10-22 19:26 被阅读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. 题目关键词

    • 难度等级:easy
    • 关键词:
    • 语言: C++

    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;
        }
    };
    

    相关文章

      网友评论

          本文标题:1051. Height Checker

          本文链接:https://www.haomeiwen.com/subject/xsrcvctx.html