-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinearsearch.js
63 lines (56 loc) · 1.58 KB
/
linearsearch.js
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//In linear search, we traverse through the array to check if any element matches the key.
function linearSearch(array, target) {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) {
//checks if element matches the key
return i;
}
}
return -1;
}
const array = [5, 10, 15, 20, 25];
const target = 15;
console.log(linearSearch(array, target));
//"Write a function that takes an array of strings and a target string as input and
// returns the index of the target string in the array using linear search.
/// If the target string is not found in the array, the function should return -1."
function linearSearchString(array, target) {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) {
return i;
}
}
return -1;
}
console.log(
linearSearchString(["apple", "banana", "orange", "pear"], "banana")
);
//array intersection
function arrayIntersection(nums1, nums2) {
let result = [];
for (let i = 0; i < nums1.length; i++) {
for (let j = 0; j < nums2.length; j++) {
if (nums1[i] === nums2[j]) {
if (!result.includes(nums1[i])) {
result.push(nums1[i]);
}
}
}
}
return result;
}
console.log(arrayIntersection([1, 2, 2, 1], [2, 2]));
//using hash map
function arrayIntersectionHash(nums1, nums2) {
const result = [];
const set = new Set(nums1);
for (let i = 0; i < nums2.length; i++) {
if (set.has(nums2[i])) {
if (!result.includes(nums1[i])) {
result.push(nums2[i]);
}
}
}
return result;
}
console.log(arrayIntersectionHash([1, 2, 2, 1], [2, 2]));