1051. Height Checker
题目文本会按所选界面语言从俄语翻译;代码保持不变。
Школа пытается сделать ежегодную фото图ию всех учеников. Учеников просят встать в одну шеренгу в неубывающем порядке по росту. Пусть этот порядок представлен целочисленным 数组ом 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 已显示.
目前还没有活跃职位。