티스토리 뷰
find the smallest distance in a given array.
const arr = [1, 4, 2, 2, 1, 5];
function smallestDistance(arr) {
const distanceArray = [];
for (let i = 0; i < arr.length; i++) {
if (arr.lastIndexOf(arr[i]) !== arr.indexOf(arr[i])) {
let distance = arr.lastIndexOf(arr[i]) - arr.indexOf(arr[i]) //get the distance
distanceArray.push(distance); //push to new array
}
}
distanceArray.sort() //sort
console.log(distanceArray[0]) //return first index
}
smallestDistance(arr); //1
'Algorithms' 카테고리의 다른 글
| How many typos in a string (0) | 2021.02.12 |
|---|---|
| CamelCase (0) | 2021.02.12 |
| Cut the sticks (0) | 2020.12.18 |
| Equalize the Array (0) | 2020.12.11 |
| Invert Binary Tree (0) | 2020.11.30 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- spring boot application
- 알고리즘
- compareTo()
- 프로그래머스 알고리즘
- rest parameter
- easy javascript algorithm
- hackerrank solution
- java
- equals()
- Javascript Algorithm
- HackerRank Algorithm
- code refactoring
- Object type casting
- HashMap
- substring()
- hackerrank javascript solution
- math.max
- algorithm
- C++
- easy algorithm
- repeat()
- math.abs
- hackerrank javascript
- ... in Javascript
- string class in java
- javascript
- hackerrank
- 프로그래머스
- Collection Framework
- 프로그래머스 알고리즘문제
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함