[HAI] week3 intersection array
https://www.interviewbit.com/problems/intersection-of-sorted-arrays/main
parent
656b5c6eb5
commit
807a5ae9cf
@ -0,0 +1,3 @@
|
|||||||
|
import { intersectionSortedArray } from "./intersectionSortedArray";
|
||||||
|
|
||||||
|
export default intersectionSortedArray;
|
||||||
@ -0,0 +1,13 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { intersectionSortedArray } from "./intersectionSortedArray.ts";
|
||||||
|
|
||||||
|
describe("intersectionSortedArray", () => {
|
||||||
|
|
||||||
|
it("[1,2,3,3,4,5,6] [3,3,5] => [3,3,5]", () => {
|
||||||
|
expect(intersectionSortedArray([1, 2, 3, 3, 4, 5, 6], [3, 3, 5])).toEqual([3, 3, 5]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("[1,2,3,4,5,6] [3,5] => [3,5]", () => {
|
||||||
|
expect(intersectionSortedArray([1, 2, 3, 4, 5, 6], [3, 5])).toEqual([3, 5]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@ -0,0 +1,20 @@
|
|||||||
|
export function intersectionSortedArray(a: number[], b: number[]): number[] {
|
||||||
|
let res: number[] = [];
|
||||||
|
let aI = 0;
|
||||||
|
let bI = 0;
|
||||||
|
|
||||||
|
while (aI < a.length && bI < b.length) {
|
||||||
|
let aValue = a[aI];
|
||||||
|
let bValue = b[bI];
|
||||||
|
|
||||||
|
if (aValue === bValue) {
|
||||||
|
res.push(aValue);
|
||||||
|
aI++;
|
||||||
|
bI++;
|
||||||
|
} else {
|
||||||
|
aValue < bValue ? aI++ : bI++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
};
|
||||||
Loading…
Reference in New Issue