728x90
Problem
Complexity
Time complexity: O(n^2)
Code
/**
Height Checker
- students stand in single file line in non-decreasing order
- expected[i] -> i'th student
- heights : current order array
- return numbers of indices where heights[i] not equal to expected[i]
*/
const heights = [1,1,4,2,1,3]
const expected = [1,1,1,2,3,4]
var heightChecker = function(heights) {
const expected = [...heights]
// Get sorted array with bubble sort
has_swapped = true;
let count = 0;
while (has_swapped) {
has_swapped = false;
for(let i = 0; i < expected.length; i++) {
if(expected[i] > expected[i+1]) {
[expected[i], expected[i+1]] = [expected[i+1], expected[i]]
has_swapped = true;
}
}
}
// Get different elements by filtering
const matchedElements = heights.filter((el, idx) => el != expected[idx])
// return the numbers of different elements
return matchedElements.length;
};
console.log(heightChecker(heights))
728x90
'Research > Coding Test' 카테고리의 다른 글
프로그래머스_lv0_안전지대 (0) | 2023.11.17 |
---|---|
해시_완주하지 못한 선수 (0) | 2023.11.16 |
HackerRank_Apple and Orange (0) | 2023.04.12 |
Leetcode_121. Best Time to Buy and Sell Stock (0) | 2023.04.06 |
HackerRank_Grading Students (0) | 2023.04.05 |
댓글