본문 바로가기
카테고리 없음

[Leetcode/JS] 350. Intersection of Two Arrays II

by 질서정연_ 2023. 7. 18.

 

문제링크 

350. Intersection of Two Arrays II
 
 

Intersection of Two Arrays II - LeetCode

Can you solve this real interview question? Intersection of Two Arrays II - Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return

leetcode.com

 
 
 

기억하면 좋을 것 

intersection 은 교차점 이라는 뜻 !

easy 라고 쉽게 봤다가 엄청 오래 걸렸다 ... 제발 꼼꼼히 문제를 보자 ㅠㅠㅠㅠ

array.splice( start , deleteCount, item0 , item1 ...)

array.splice를 처음 써봤다... 반성한다...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice 

 

Array.prototype.splice() - JavaScript | MDN

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

developer.mozilla.org

 

splice 는

start 에 삭제 혹은 변경을 시작할 index

deleteCount 에 start 부터 삭제를 할 갯수 

item0... 에 삭제 / 변경을 한 후 배열에 삽입 할 요소들을 적으면 된다. (deleteCount 가 0 이거나 false 라면 item이 필수)

 

const months = ['Jan', 'March', 'April', 'June', 'Hellp', 'Happy'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 2, 'May');
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]

months.splice(1,1);
console.log(months);

months.splice(0,2,'HI', "HEHE", "KING");
console.log(months);

 

findIndex , find, indexOf 차이 - findIndex(함수)파라미터로 함수를 받는다. 찾은 요소 인덱스를 리턴한다. 못찾으면 -1 return.- find(함수)파라미터로 함수를 받는다. 찾은 요소 값 자체를 리턴한다. 못찾으면 undefined return.- indexOf(값 , 탐색 시작 할 인덱스(옵션) ) 파라미터로 값을 받는다. 찾은 요소 인덱스를 리턴한다. 못찾으면 -1 return .

 

소감

easy 라고 만만하게 보지 말자 ... 

 

해결 코드

처음 코드 
 
var intersect = function(nums1, nums2) {
    let result = [];

    for(let i of nums1){
        for(let j=0 ; j<nums2.length ; j++){
            if(i === nums2[j]){
                result.push(i);
                nums2 = [...nums2.slice(0,j), ...nums2.slice(j+1)];
                break;
            }
        }
    }
    return result;
};
 
처음에 for문도 두개써서 n(O^2) 였고 같은게 있을 때 마다 배열을 다시 선언 해 줬어서 시간복잡도랑 공간복잡도가 엄청 크게 나왔었다.
 
다른 사람 풀이 
var intersect = function(nums1, nums2){
    let result = [];
    for(let i = 0; i<nums1.length ; i++){
        if( nums2.includes(nums1[i]) ) {
            result.push(nums1[i]);
            nums2.splice(nums2.indexOf(nums1[i]),1);
        }  
    }
    return result;
}

splice 써서 for 문 한번만 돌고 splice써서 배열 자체를 재선언 하지 않고 수정 해 주니까 시간복잡도 공간복잡도 모두 좋아졌다.

Submission Detail

처음 풀이 

수정한 풀이 

배열 수정 , 특정 요소 삭제를 할 때에는 splice를 쓰자.

 

댓글