배열

js·2021년 10월 13일
0

1. 배열의 중복제거

Set에 담아서 중복을 제거한다

const dupArr = [1, 2, 3, 1, 2];
const set = new Set(dupArr);
const uniqueArr = [...set];

console.log(uniqueArr)  // [1, 2, 3]

2. 정렬을 유지하면서 배열 합치기

function merge(num1,num2){
	let i=num1.length-1;
    let j=num2.length-1;
    let k=num1.length+num2.length-1;
    
    while(i>=0 && j>=0){
    	if(num1[i] < num2[i]){
        	num1[k] = num2[j];
            j-=1;
       	} else{
        	num1[k] = num1[i];
            i-=1;
        }
        k-=1;
    }
    while(j>=0){
    	k-=1;
        j-=1;
    }
}

3. 배열안에 가장 많이 들어있는 요소 구하기

function majority(nums){
	return nums.sort()[Math.floor(nums.length/2)];
}

4. 배열의 요소들을 우측으로 k만큼 이동시키기

function rotate(nums, k){
	const temp = Array.from({length: 5}, () => 0);
    for(let i=0; i<temp.length-1; i++){
    	temp[(i+k) % nums.length]=nums[i];
    }
    temp.forEach((curr,idx)=> nums[idx]=curr);

}

5. 부분 집합(모든 조합 구하기)

//nums: 배열, answer: 부분집합 배열, sub: 임시 배열, idx: 인덱스

function subset_recursion(nums, answer, sub, idx){
	if( sub.length > nums.length){
    	return;
    }
    res.push(sub.slice());
    for(let i=idx; i<nums.length; i++){
    	sub.push(nums[i]);
        subset_recursion(nums, answer, sub, i+1);
        sub.pop();
    }
}

0개의 댓글