1051. Height Checker

LeetCode easy original: C# #array #csharp #easy #graph #leetcode #queue #sort
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.

Школа пытается сделать ежегодную фотоgrapheию всех учеников. Учеников просят встать в одну шеренгу в неубывающем порядке по росту. Пусть этот порядок представлен целочисленным tableauом expected, где expected[i] - ожидаемый рост i-го студента в очереди. Вам дан entier tableau heights, представляющий текущий порядок, в котором стоят студенты. Каждый heights[i] - это высота i-го студента в очереди (с индексом 0). return количество индексов, в которых heights[i] != expected[i].

Exemple:

Input: heights = [1,1,4,2,1,3]

Output: 3

C# solution

correspondant/original
public class Solution {
    public int HeightChecker(int[] heights) {
        int[] expected = (int[])heights.Clone();
        Array.Sort(expected);
        int count = 0;
        for (int i = 0; i < heights.Length; i++) {
            if (heights[i] != expected[i]) {
                count++;
            }
        }
        return count;
    }
}

C++ solution

brouillon automatique, à relire avant soumission
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int HeightChecker(vector<int>& heights) {
        vector<int>& expected = (int[])heights.Clone();
        sort(expected.begin(), expected.end());
        int count = 0;
        for (int i = 0; i < heights.size(); i++) {
            if (heights[i] != expected[i]) {
                count++;
            }
        }
        return count;
    }
}

Java solution

correspondant/original
import java.util.Arrays;

public class Solution {
    public int heightChecker(int[] heights) {
        int[] expected = heights.clone();
        Arrays.sort(expected);
        int count = 0;
        for (int i = 0; i < heights.length; i++) {
            if (heights[i] != expected[i]) {
                count += 1;
            }
        }
        return count;
    }
}

JavaScript solution

correspondant/original
function heightChecker(heights) {
    let expected = [...heights].sort((a, b) => a - b);
    let count = 0;
    for (let i = 0; i < heights.length; i++) {
        if (heights[i] !== expected[i]) {
            count++;
        }
    }
    return count;
}

Python solution

correspondant/original
def heightChecker(heights):
    expected = sorted(heights)
    count = 0
    for i in range(len(heights)):
        if heights[i] != expected[i]:
            count += 1
    return count

Go solution

correspondant/original
package main

import (
    "fmt"
    "sort"
)

func heightChecker(heights []int) int {
    expected := make([]int, len(heights))
    copy(expected, heights)
    sort.Ints(expected)
    count := 0
    for i := range heights {
        if heights[i] != expected[i] {
            count++
        }
    }
    return count
}

Algorithm

1⃣Создай отсортированную копию tableauа heights, чтобы получить ожидаемый порядок высот.

2⃣Пройди по обоим tableauам и сравни elementы.

3⃣Подсчитай количество индексов, где elementы двух tableauов не равны

😎

Vacancies for this task

offres actives with overlapping task tags are affichés.

Toutes les offres
Il n'y a pas encore d'offres actives.