当前位置:网站首页>Leetcode-1051: height checker

Leetcode-1051: height checker

2022-06-24 10:24:00 Ugly and ugly

Title Description

The school plans to take an annual commemorative photo for all the students . According to the requirements , Students need to follow The decreasing Line up in order of height .
The sorted height is an integer array expected Express , among expected[i] It's expected to be number... In this line i The height of a student ( Subscript from 0 Start ).
Give you an array of integers heights , Indicates the height of the current student position .heights[i] It's the... In this line i The height of a student ( Subscript from 0 Start ).
Return to satisfaction heights[i] != expected[i] Number of subscripts for .

Example

Example 1:
Input :heights = [1,1,4,2,1,3]
Output :3
explain :
Height :[1,1,4,2,1,3]
expect :[1,1,1,2,3,4]
Subscript 2 、4 、5 The height of the students at does not match .

Example 2:
Input :heights = [5,1,2,3,4]
Output :5
explain :
Height :[5,1,2,3,4]
expect :[1,2,3,4,5]
The corresponding student heights of all subscripts do not match .

Example 3:
Input :heights = [1,2,3,4,5]
Output :0
explain :
Height :[1,2,3,4,5]
expect :[1,2,3,4,5]
The corresponding student heights of all subscripts match .

The problem solving process

Ideas and steps

(1) Simple questions . Consider space for time .
(2) New development data , And sort in ascending order ;
(3) Traverse two arrays , Count the number of different elements in the same position between the sorted array and the original array , It's the end result .

Code display

public class HeightChecker {
    

    public int heightChecker(int[] heights) {
    
        //  Open up new data ,  Sort ,  Compare the new array data with the original array data 
        int[] tempArray = Arrays.copyOf(heights, heights.length);
        Arrays.sort(tempArray);
        int count = 0;
        for (int i = 0; i < heights.length; i++) {
    
            if (tempArray[i] != heights[i]) {
    
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
    
        int[] heights = {
    5,1,2,3,4,6};
        System.out.println(new HeightChecker().heightChecker(heights));
    }

}
原网站

版权声明
本文为[Ugly and ugly]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240916245027.html