当前位置:网站首页>LeetCode-高度检查器

LeetCode-高度检查器

2022-06-21 12:06:00 尖兵果子

学校打算为全体学生拍一张年度纪念照。根据要求,学生需要按照 非递减 的高度顺序排成一行。
排序后的高度情况用整数数组 expected 表示,其中 expected[i] 是预计排在这一行中第 i 位的学生的高度(下标从 0 开始)。
给你一个整数数组 heights ,表示 当前学生站位 的高度情况。heights[i] 是这一行中第 i 位学生的高度(下标从 0 开始)。
返回满足 heights[i] != expected[i] 的 下标数量 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/height-checker

分析

题目说的复杂,用自己话说就是看这个队伍里有多少人没有按序排队,要求的就是这些人的数量

那么解题步骤如下

  1. 将待排序数组存入新数组
  2. 对待排序数组排序
  3. 将排序后的数组与新数组比较
  4. 返回不同数的数量

C代码

void sort(int heightsSize,int *heights)
{
    
    for(int i=0;i<heightsSize;i++)
    {
    
        for(int j=0;j<heightsSize-i-1;j++)
        {
    
            if(heights[j]>heights[j+1])
            {
    
                int temp=heights[j];
                heights[j]=heights[j+1];
                heights[j+1]=temp;
            }
        }
    }
}

int heightChecker(int* heights, int heightsSize){
    
    int res[heightsSize];
    int index=0,count=0;

    while(index<heightsSize)
    {
    
        res[index]=heights[index];
        index++;
    }

    sort(heightsSize,heights);

    index=0;
    
    while(index<heightsSize)
    {
    
        if(res[index]!=heights[index])
        {
    
            count++;
        }
        index++;
    }

    return count;
}

JS代码

/** * @param {number[]} heights * @return {number} */
var heightChecker = function(heights) {
    
    let res=JSON.parse(JSON.stringify(heights));
    let count=0;

    heights.sort((num1,num2)=>num1-num2)

    res.forEach((item,index)=>{
    
        if(item!=heights[index])
        {
    
            count++;
        }
    })

    return count;
};

let res=JSON.parse(JSON.stringify(heights));写这一句话是因为直接将数组赋给新数组,在JS中属于浅拷贝,也就是两个数据连体,一变都变.这一句话的作用是将其变成深拷贝的形式,也就是两个不相干的数组

有关JS深浅拷贝内容,本人也不是很了解,待学习后定来完善

原网站

版权声明
本文为[尖兵果子]所创,转载请带上原文链接,感谢
https://blog.csdn.net/wfy17030212/article/details/125349258