mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-17 01:06:07 +00:00
Add ru version (#1865)
* Add Russian docs site baseline * Add Russian localized codebase * Polish Russian code wording * Update ru code translation. * Update code translation and chapter covers. * Fix pythontutor extraction. * Add README and landing page. * placeholder of profiles * Use figures of English version * Remove chapter paperbook
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* File: linear_search.js
|
||||
* Created Time: 2022-12-22
|
||||
* Author: JoseHung (szhong@link.cuhk.edu.hk)
|
||||
*/
|
||||
|
||||
const { ListNode, arrToLinkedList } = require('../modules/ListNode');
|
||||
|
||||
/* Линейный поиск (массив) */
|
||||
function linearSearchArray(nums, target) {
|
||||
// Обход массива
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
// Целевой элемент найден, вернуть его индекс
|
||||
if (nums[i] === target) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
// Целевой элемент не найден, вернуть -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Линейный поиск (связный список) */
|
||||
function linearSearchLinkedList(head, target) {
|
||||
// Обойти связный список
|
||||
while (head) {
|
||||
// Найти целевой узел и вернуть его
|
||||
if (head.val === target) {
|
||||
return head;
|
||||
}
|
||||
head = head.next;
|
||||
}
|
||||
// Целевой узел не найден, вернуть null
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const target = 3;
|
||||
|
||||
/* Выполнить линейный поиск в массиве */
|
||||
const nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
const index = linearSearchArray(nums, target);
|
||||
console.log('Индекс целевого элемента 3 = ' + index);
|
||||
|
||||
/* Выполнить линейный поиск в связном списке */
|
||||
const head = arrToLinkedList(nums);
|
||||
const node = linearSearchLinkedList(head, target);
|
||||
console.log('Объект узла со значением 3 = ', node);
|
||||
Reference in New Issue
Block a user