1051. Height Checker

LeetCode easy original: C# #array #csharp #easy #graph #leetcode #queue #sort
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

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

예제:

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

Output: 3

C# 해법

매칭됨/원본
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++ 해법

자동 초안, 제출 전 검토
#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 해법

매칭됨/원본
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 해법

매칭됨/원본
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 해법

매칭됨/원본
def heightChecker(heights):
    expected = sorted(heights)
    count = 0
    for i in range(len(heights)):
        if heights[i] != expected[i]:
            count += 1
    return count

Go 해법

매칭됨/원본
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⃣Создай отсортированную копию 배열а heights, чтобы получить ожидаемый порядок высот.

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

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

😎

Vacancies for this task

활성 채용 with overlapping task tags are 표시됨.

전체 채용
아직 활성 채용이 없습니다.