mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-02 03:05:24 +08:00
* Retranslate the complete Japanese online edition from Chinese * Fit Japanese homepage labels and localize heading permalinks * Point Japanese contribution instructions to the Japanese preview * Replace locale conditionals with multilingual UI tables
48 lines
1.4 KiB
JavaScript
48 lines
1.4 KiB
JavaScript
/**
|
|
* File: linear_search.js
|
|
* Created Time: 2022-12-22
|
|
* Author: JoseHung ([email protected])
|
|
*/
|
|
|
|
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;
|
|
}
|
|
|
|
/* 実行用コード */
|
|
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);
|