Skip to content

Commit 2b8fa0b

Browse files
authored
Merge branch 'master' into patch-1
2 parents e0f6b2d + e7f30a7 commit 2b8fa0b

File tree

8 files changed

+105
-22
lines changed

8 files changed

+105
-22
lines changed

README.ar-AR.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
[![Build Status](https://travis-ci.org/trekhleb/javascript-algorithms.svg?branch=master)](https://travis-ci.org/trekhleb/javascript-algorithms)
44
[![codecov](https://codecov.io/gh/trekhleb/javascript-algorithms/branch/master/graph/badge.svg)](https://codecov.io/gh/trekhleb/javascript-algorithms)
55

6-
تحتوي هذا مقالة على أمثلة عديدة تستند إلى الخوارزميات الشائعة وهياكل البيانات في الجافا سكريبت.
6+
تحتوي هذه المقالة على أمثلة عديدة تستند إلى الخوارزميات الشائعة وهياكل البيانات في الجافا سكريبت.
77

88
كل خوارزمية وهياكل البيانات لها برنامج README منفصل خاص بها
99
مع التفسيرات والروابط ذات الصلة لمزيد من القراءة (بما في ذلك تلك

README.es-ES.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ definen con precisión una secuencia de operaciones.
7070
* **Matemáticas**
7171
* `P` [Manipulación de bits](src/algorithms/math/bits) - asignar/obtener/actualizar/limpiar bits, multiplicación/división por dos, hacer negativo, etc.
7272
* `P` [Factorial](src/algorithms/math/factorial)
73-
* `P` [Número de Fibonacci](src/algorithms/math/fibonacci)
73+
* `P` [Sucesión de Fibonacci](src/algorithms/math/fibonacci)
7474
* `P` [Prueba de primalidad](src/algorithms/math/primality-test) (método de división de prueba)
7575
* `P` [Algoritmo de Euclides](src/algorithms/math/euclidean-algorithm) - calcular el Máximo común divisor (MCD)
7676
* `P` [Mínimo común múltiplo](src/algorithms/math/least-common-multiple) (MCM)
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Búsqueda binaria
2+
3+
_Lea esto en otros idiomas:_
4+
[English](README.md)
5+
[Português brasileiro](README.pt-BR.md).
6+
7+
En informática, la búsqueda binaria, también conocida como búsqueda de medio intervalo
8+
búsqueda, búsqueda logarítmica, o corte binario, es un algoritmo de búsqueda
9+
que encuentra la posición de un valor objetivo dentro de una matriz
10+
ordenada. La búsqueda binaria compara el valor objetivo con el elemento central
11+
de la matriz; si son desiguales, se elimina la mitad en la que
12+
la mitad en la que no puede estar el objetivo se elimina y la búsqueda continúa
13+
en la mitad restante hasta que tenga éxito. Si la búsqueda
14+
termina con la mitad restante vacía, el objetivo no está
15+
en la matriz.
16+
17+
![Búsqueda binaria](https://upload.wikimedia.org/wikipedia/commons/8/83/Binary_Search_Depiction.svg)
18+
19+
## Complejidad
20+
21+
**Complejidad de tiempo**: `O(log(n))` - ya que dividimos el área de búsqueda en dos para cada
22+
siguiente iteración.
23+
24+
## Referencias
25+
26+
- [Wikipedia](https://en.wikipedia.org/wiki/Binary_search_algorithm)
27+
- [YouTube](https://www.youtube.com/watch?v=P3YID7liBug&index=29&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)

src/algorithms/search/binary-search/README.md

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,16 @@
22

33
_Read this in other languages:_
44
[Português brasileiro](README.pt-BR.md).
5+
[Español](README.es-ES.md).
56

6-
In computer science, binary search, also known as half-interval
7-
search, logarithmic search, or binary chop, is a search algorithm
8-
that finds the position of a target value within a sorted
9-
array. Binary search compares the target value to the middle
10-
element of the array; if they are unequal, the half in which
11-
the target cannot lie is eliminated and the search continues
12-
on the remaining half until it is successful. If the search
13-
ends with the remaining half being empty, the target is not
7+
In computer science, binary search, also known as half-interval
8+
search, logarithmic search, or binary chop, is a search algorithm
9+
that finds the position of a target value within a sorted
10+
array. Binary search compares the target value to the middle
11+
element of the array; if they are unequal, the half in which
12+
the target cannot lie is eliminated and the search continues
13+
on the remaining half until it is successful. If the search
14+
ends with the remaining half being empty, the target is not
1415
in the array.
1516

1617
![Binary Search](https://upload.wikimedia.org/wikipedia/commons/8/83/Binary_Search_Depiction.svg)

src/algorithms/search/binary-search/README.pt-BR.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
_Leia isso em outras línguas:_
44
[english](README.md).
5+
[Español](README.es-ES.md).
56

67
Em ciência da computação, busca binária, também conhecida como busca de meio-intervalo, busca logarítmica ou corte binário, é um algoritmo de pesquisa
78
que encontra a posição de um elemento alvo dentro de um

src/data-structures/linked-list/README.es-ES.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ _Lee este artículo en otros idiomas:_
77
[_Português_](README.pt-BR.md)
88
[_English_](README.md)
99

10-
En ciencias de la computaciòn una **lista enlazada** es una coleccion linear
11-
de elementos de datos, en los cuales el orden linear no es dado por
12-
su posciòn fisica en memoria. En cambio, cada
10+
En ciencias de la computación una **lista enlazada** es una colección lineal
11+
de elementos, en los cuales el orden lineal no es dado por
12+
su posición física en memoria. En cambio, cada
1313
elemento señala al siguiente. Es una estructura de datos
1414
que consiste en un grupo de nodos los cuales juntos representan
1515
una secuencia. En su forma más sencilla, cada nodo está
@@ -19,10 +19,10 @@ permite la inserción o eliminación de elementos
1919
desde cualquier posición en la secuencia durante la iteración.
2020
Las variantes más complejas agregan enlaces adicionales, permitiendo
2121
una eficiente inserción o eliminación desde referencias arbitrarias
22-
del elemento. Una desventaja de las listas lazadas es que el tiempo de
22+
del elemento. Una desventaja de las listas enlazadas es que el tiempo de
2323
acceso es lineal (y difícil de canalizar). Un acceso
2424
más rápido, como un acceso aleatorio, no es factible. Los arreglos
25-
tienen una mejor locazion en caché comparados con las listas lazadas.
25+
tienen una mejor localización en caché comparados con las listas enlazadas.
2626

2727
![Linked List](./images/linked-list.jpeg)
2828

@@ -112,7 +112,7 @@ Remove(head, value)
112112
end Remove
113113
```
114114

115-
### Atrevesar
115+
### Atravesar
116116

117117
```text
118118
Traverse(head)
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# LRU 캐시 알고리즘
2+
3+
**LRU 캐시 알고리즘** 은 사용된 순서대로 아이템을 정리함으로써, 오랜 시간 동안 사용되지 않은 아이템을 빠르게 찾아낼 수 있도록 한다.
4+
5+
한방향으로만 옷을 걸 수 있는 옷걸이 행거를 생각해봅시다. 가장 오랫동안 입지 않은 옷을 찾기 위해서는, 행거의 반대쪽 끝을 보면 됩니다.
6+
7+
## 문제 정의
8+
9+
LRUCache 클래스를 구현해봅시다:
10+
11+
- `LRUCache(int capacity)` LRU 캐시를 **양수**`capacity` 로 초기화합니다.
12+
- `int get(int key)` `key` 가 존재할 경우 `key` 값을 반환하고, 그렇지 않으면 `undefined` 를 반환합니다.
13+
- `void set(int key, int value)` `key` 가 존재할 경우 `key` 값을 업데이트 하고, 그렇지 않으면 `key-value` 쌍을 캐시에 추가합니다. 만약 이 동작으로 인해 키 개수가 `capacity` 를 넘는 경우, 가장 오래된 키 값을 **제거** 합니다.
14+
15+
`get()``set()` 함수는 무조건 평균 `O(1)` 의 시간 복잡도 내에 실행되어야 합니다.
16+
17+
## 구현
18+
19+
### 버전 1: 더블 링크드 리스트 + 해시맵
20+
21+
[LRUCache.js](./LRUCache.js) 에서 `LRUCache` 구현체 예시를 확인할 수 있습니다. 예시에서는 (평균적으로) 빠른 `O(1)` 캐시 아이템 접근을 위해 `HashMap` 을 사용했고, (평균적으로) 빠른 `O(1)` 캐시 아이템 수정과 제거를 위해 `DoublyLinkedList` 를 사용했습니다. (허용된 최대의 캐시 용량을 유지하기 위해)
22+
23+
![Linked List](./images/lru-cache.jpg)
24+
25+
_[okso.app](https://okso.app) 으로 만듦_
26+
27+
LRU 캐시가 어떻게 작동하는지 더 많은 예시로 확인하고 싶다면 LRUCache.test.js](./**test**/LRUCache.test.js) 파일을 참고하세요.
28+
29+
### 버전 2: 정렬된 맵
30+
31+
더블 링크드 리스트로 구현한 첫번째 예시는 어떻게 평균 `O(1)` 시간 복잡도가 `set()``get()` 으로 나올 수 있는지 학습 목적과 이해를 돕기 위해 좋은 예시입니다.
32+
33+
그러나, 더 쉬운 방법은 자바스크립트의 [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) 객체를 사용하는 것입니다. 이 `Map` 객체는 키-값 쌍과 키를 **추가하는 순서 원본** 을 지닙니다. 우리는 이걸 아이템을 제거하거나 다시 추가하면서 맵의 "가장 마지막" 동작에서 최근에 사용된 아이템을 유지하기 위해 사용할 수 있습니다. `Map` 의 시작점에 있는 아이템은 캐시 용량이 넘칠 경우 가장 먼저 제거되는 대상입니다. 아이템의 순서는 `map.keys()` 와 같은 `IterableIterator` 을 사용해 확인할 수 있습니다.
34+
35+
해당 구현체는 [LRUCacheOnMap.js](./LRUCacheOnMap.js)`LRUCacheOnMap` 예시에서 확인할 수 있습니다.
36+
37+
이 LRU 캐시 방식이 어떻게 작동하는지 더 많은 테스트 케이스를 확인하고 싶다면 [LRUCacheOnMap.test.js](./__test__/LRUCacheOnMap.test.js) 파일을 참고하세요.
38+
39+
## 복잡도
40+
41+
| | 평균 |
42+
| --------------- | ------ |
43+
| 공간 | `O(n)` |
44+
| 아이템 찾기 | `O(1)` |
45+
| 아이템 설정하기 | `O(1)` |
46+
47+
## 참조
48+
49+
- [LRU Cache on LeetCode](https://leetcode.com/problems/lru-cache/solutions/244744/lru-cache/)
50+
- [LRU Cache on InterviewCake](https://www.interviewcake.com/concept/java/lru-cache)
51+
- [LRU Cache on Wiki](https://en.wikipedia.org/wiki/Cache_replacement_policies)

src/data-structures/lru-cache/README.md

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# Least Recently Used (LRU) Cache
22

3+
_Read this in other languages:_
4+
[한국어](README.ko-KR.md),
5+
36
A **Least Recently Used (LRU) Cache** organizes items in order of use, allowing you to quickly identify which item hasn't been used for the longest amount of time.
47

58
Picture a clothes rack, where clothes are always hung up on one side. To find the least-recently used item, look at the item on the other end of the rack.
@@ -22,7 +25,7 @@ See the `LRUCache` implementation example in [LRUCache.js](./LRUCache.js). The s
2225

2326
![Linked List](./images/lru-cache.jpg)
2427

25-
*Made with [okso.app](https://okso.app)*
28+
_Made with [okso.app](https://okso.app)_
2629

2730
You may also find more test-case examples of how the LRU Cache works in [LRUCache.test.js](./__test__/LRUCache.test.js) file.
2831

@@ -38,11 +41,11 @@ You may also find more test-case examples of how the LRU Cache works in [LRUCach
3841

3942
## Complexities
4043

41-
| | Average |
42-
|---|---|
43-
| Space |`O(n)`|
44-
| Get item | `O(1)` |
45-
| Set item | `O(1)` |
44+
| | Average |
45+
| -------- | ------- |
46+
| Space | `O(n)` |
47+
| Get item | `O(1)` |
48+
| Set item | `O(1)` |
4649

4750
## References
4851

0 commit comments

Comments
 (0)