알고리즘/해결

LeetCode1051. Height Checker

언클린 2020. 3. 25. 20:58
728x90

1. 문제(원본)

Students are asked to stand in non-decreasing order of heights for an annual photo.

Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.

Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats.

 

Example 1:

Input: heights = [1,1,4,2,1,3] Output: 3 Explanation: Current array : [1,1,4,2,1,3] Target array : [1,1,1,2,3,4] On index 2 (0-based) we have 4 vs 1 so we have to move this student. On index 4 (0-based) we have 1 vs 3 so we have to move this student. On index 5 (0-based) we have 3 vs 4 so we have to move this student.

Example 2:

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

Example 3:

Input: heights = [1,2,3,4,5] Output: 0

 

Constraints:

  • 1 <= heights.length <= 100
  • 1 <= heights[i] <= 100

2. 문제

삽입 정렬

3. 나의 답

class Solution {

    func heightChecker(_ heights: [Int]) -> Int {

        var count = 0

        let sorted = heights.sorted()

        for (index, element) in heights.enumerated() where sorted[index] != element {

            count += 1

        }

        return count

    }

}

4. 다른 유저의 답

#1

func heightChecker(_ heights: [Int]) -> Int {

    return heights.sorted().enumerated().reduce(0) {

        $0 + ($1.element != heights[$1.offset] ? 1 : 0)

    }

}

 

#2

class Solution {

    func heightChecker(_ heights: [Int]) -> Int {

        var sortedHeights = heights.sorted()

        return sortedHeights.enumerated().reduce(0, { (accumulator, current) in

            return accumulator + (heights[current.0] != current.1 ? 1 : 0)

        })

    }

}

5. 마무리

배열의 reduce를 생각지도 못했다. 다른 유저들의 답을 보고 왜 reduce를 사용해서 좀 더 간략화 할 생각을 하지 못했나 하는 생각 뿐이었다. 아직 배열의 활용이 부족한 것 같다. 좀 더 익숙해질 수 있도록 해야겠다.

728x90