-
[leetcode] Height Checker알고리즘 2021. 8. 24. 22:19
https://leetcode.com/explore/learn/card/fun-with-arrays/523/conclusion/3228/
특정 배열이 주어졌을때 해당 배열을 오름차순으로 정렬할 시 몇개의 원소를 이동해야 하는가에 대한 문제이다.
일단, 입력받은 배열만큼의 동일한 배열을 새로 생성한 후 값을 복사해주었다.
동일한 값을 가진 두개의 배열에서 배열 하나는 정렬을 진행한 후에 반복문을 통해 정렬되지 않은 배열과 인덱스의 값을 비교하여 다른 경우에만 카운트를 올린 후에 리턴해주었다.
class Solution { public int heightChecker(int[] heights) { if (heights == null) return -1; int[] tmpHeights = new int[heights.length]; for (int i=0; i<heights.length; i++) { tmpHeights[i] = heights[i]; } Arrays.sort(heights); int count = 0; for (int i=0; i<heights.length; i++) { if (tmpHeights[i] != heights[i]) { count++; } } return count; } }
'알고리즘' 카테고리의 다른 글
[leetcode] Max Consecutive Ones II (0) 2021.09.03 [코딩인터뷰완전분석] 1.2_순열확인_풀이 (0) 2021.08.24 [코딩인터뷰완전분석] 1.1_중복이 없는가_풀이 (0) 2021.08.24 알고리즘 학습법 (0) 2021.08.21 [LeetCode] Palindrome Number (0) 2021.06.22