Skip to content

Comments

[imchanyo] 25.01.05 #12

Merged
JooKangsan merged 8 commits intomainfrom
origin/imchanyo
Jan 9, 2025
Merged

[imchanyo] 25.01.05 #12
JooKangsan merged 8 commits intomainfrom
origin/imchanyo

Conversation

@imchanyo
Copy link
Collaborator

@imchanyo imchanyo commented Jan 5, 2025

[배열]

📌 푼 문제


📝 간단한 풀이 과정

배열 자르기

  • splice를 이용하여 원본 배열의 인덱스로 접근하여 새로운 배열을 반환했습니다.
function solution(numbers, num1, num2) {
  var answer = [];
  answer = numbers.splice(num1, num2);
  return answer;
}

중복된 숫자 개수

function solution(array, n) {
 var answer = [];

 array.forEach((num) => {
   if (num === n) {
     answer.push(num);
   }
 });

 return answer.length;
}

배열 회전시키기

  • 첫번째는 es문법에서 제공하는 배열 함수인 pop, unshift, push, shift를 사용하여 작성했습니다.
  • 두번째는, slice를 연습할겸 사용했습니다.
  • 세번째는, splice를 연습할겸 사용했습니다.
function solution(numbers, direction) {
  var answer = [...numbers];

  if (direction === "right") {
    const rightNumbers = answer.pop();
    answer.unshift(rightNumbers);
  } else if (direction === "left") {
    const leftNumbers = answer.shift();
    answer.push(leftNumbers);
  }

  return answer;
}

/* slice 연습하기 */
function solution(numbers, direction) {
  if (direction === "right") {
    const last = numbers.slice(-1);
    const rest = numbers.slice(0, -1);
    return [...last, ...rest];
  } else if (direction === "left") {
    const first = numbers.slice(0, 1);
    const rest = numbers.slice(1);
    return [...rest, ...first];
  }
}

/* splice 연습 */
function solution(numbers, direction) {
  if (direction === "right") {
    const last = numbers.splice(-1, 1);
    numbers.unshift(...last);
  } else if (direction === "left") {
    const first = numbers.splice(0, 1);
    numbers.push(...first);
  }
  return numbers;
}

제일 작은 수 제거하기

  • 이중 for문을 통하여 하나씩 비교하여 큰 값을 푸시한 이 후, 중복 제거합니다.
function solution(arr) {
  var answer = [];

  if (arr[0] === 10) {
    return [-1];
  }

  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (arr[i] > arr[j]) {
        answer.push(arr[i]);
      }
    }
  }

  return [...new Set(answer)];
}

배열 원소의 길이

function solution(strlist) {
  var answer = [];

  strlist.forEach((string) => answer.push(string.length));
  return answer;
}

행렬의 덧셈

  • 이중 포문을 사용하여 newArr 배열에 각각 더한 값을 푸시합니다.
  • newArr의 배열을 answer에 푸시합니다.
function solution(arr1, arr2) {
  let answer = [];
  for (let i = 0; i < arr1.length; i++) {
    let newArr = [];
    for (let j = 0; j < arr1[0].length; j++) {
      newArr.push(arr1[i][j] + arr2[i][j]);
    }
    answer.push(newArr);
  }

  return answer;
}

@imchanyo imchanyo changed the title Origin/imchanyo [imchanyo] 25.01.05 Jan 5, 2025
@JooKangsan JooKangsan requested review from jiyeeeah and removed request for JooKangsan January 5, 2025 12:52
Copy link
Collaborator

@jiyeeeah jiyeeeah left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고생 많으셨습니다! slicesplice 연습까지 하시다니.. 멋지십니다!
간단한 의견만 남겨놨으니 참고해주세요 ㅎㅎ 앞으로도 화이팅입니다 😁

Comment on lines +8 to +14
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (arr[i] > arr[j]) {
answer.push(arr[i]);
}
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이렇게 하면 시간 복잡도가 올라갈 것 같은데, 최소값을 먼저 구하고 그걸로 배열을 가공하면 복잡도가 줄어들지 않을까 생각합니다!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

같은 생각입니다!

Comment on lines +4 to +6
if (arr[0] === 10) {
return [-1];
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

왜 첫번째 배열이 10인경우 [-1]return하도록 하신걸까용?
문제에서 [-1]return하는 경우는 작은 수를 제거했을 때 빈 배열만 남는 경우인 것 같아서요!

Copy link
Collaborator

@juhee067 juhee067 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

확인했습니다! 고생많으셨습니다. 덕분에 저도 배워갑니다!1

}
});

return answer.length;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드 길이를 줄이고 싶으시다면 filter라는 함수를 사용해도 좋을 것 같아요! 성능도 비슷하고!

Comment on lines +8 to +14
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (arr[i] > arr[j]) {
answer.push(arr[i]);
}
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

같은 생각입니다!


strlist.forEach((string) => answer.push(string.length));
return answer;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 방식도 좋지만 map 함수도 사용해보면 좋을 것 같아요! 그러면 좀 더 간결해집니다!

@JooKangsan JooKangsan merged commit 5900b85 into main Jan 9, 2025
4 checks passed
Copy link
Collaborator

@bona1122 bona1122 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

전체적으로 다양한 배열메서드를 사용한 점이 좋습니다.

다만, 답을 구하기위해 새로운 배열을 두어 push,pop 등의 작업을 하는 것보다는 배열메서드를 최대한 활용하거나 인덱스를 활용하는 방향이 더 좋을 것 같습니다. 시간복잡도가 중요한 문제에서는 배열에서 push,pop 작업이 시간을 많이 잡아먹는 경우가 생기더라구요! 코드 전체적으로 잘 보고갑니다 👍

Comment on lines +1 to +10
function solution(array, n) {
var answer = [];

array.forEach((num) => {
if (num === n) {
answer.push(num);
}
});

return answer.length;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

배열을 순회하면서 특정 수의 개수를 세는 것이니까, 한번만 순회하면서 답을 구하는 건 좋은 것같아요. 그런데 정답을 도출하기위해 배열하나를 더해서 push작업을 수행하고 있는데, push도 결국 배열길이가 늘어가면 비용이 커지니까 이 문제에서는 reduce나 filter를 사용하는 것이 더 좋지 않을까 합니다. 특히 이 문제는 값하나(개수)를 도출해내는 것이니까 reduce가 제일 간단할 것 같아요

const solution = (array, n) => {
    return array.reduce((acc,cur) => {
        return cur === n ? ++acc : acc;
    },0)
}

Comment on lines +16 to +26
function solution(numbers, direction) {
if (direction === "right") {
const last = numbers.slice(-1);
const rest = numbers.slice(0, -1);
return [...last, ...rest];
} else if (direction === "left") {
const first = numbers.slice(0, 1);
const rest = numbers.slice(1);
return [...rest, ...first];
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

slice함수에 음수 인덱스를 사용할 수 있는 것 리마인드 하고 갑니다 :)
연습하신 것이겠지만, 맨앞,맨마지막 요소를 구하기 위해 slice를 쓰는 것 보다는 배열인덱스로 바로 접근하는게 slice메서드 호출을 줄여줘서 좋을 것 같습니다.

const solution = (numbers, direction) => {
    if (direction === 'right'){
        return [numbers[numbers.length - 1], ...numbers.slice(0,numbers.length - 1)];
    }
    else{
        return [...numbers.slice(1), numbers[0]];
    }
}

bona1122 pushed a commit to bona1122/AlgorithmStudy that referenced this pull request Jan 9, 2025
* 배열자르기 / 기초

* 배열 원소의 길이 / 기초

* 배열 회전시키기 / 기초

* .

* 배열 회전시키기 / 로직추가 / 기초

* 중복된 숫자 개수 / 기초

* 제일 작은 수 제거하기 / 중급

* 행렬의 덧셈 /중급
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants