๐Ÿ“Œ 1. ๋ฌธ์ œ


27. Remove Element


Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesnโ€™t matter what you leave beyond the new length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.

Internally you can think of this:


Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3] Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesnโ€™t matter what values are set beyond the returned length.


โœ ํ’€์ด

var removeElement = function (nums, val) {
  for (let i = nums.length - 1; i >= 0; i--) {
    if (nums[i] === val) nums.splice(i, 1);
  }
  return nums.length;
};


  • splice๋ฅผ ์‚ฌ์šฉํ• ๋•Œ๋Š” for๋ฌธ์„ ๋˜๋„๋ก ๋’ค์—์„œ ๋Œ๋ ค์•ผ๊ฒ ๋‹ค.. ์ž๊พธ ์•ž์—์„œ ๋Œ๋ฆฌ๋‹ค๊ฐ€ index๊ฐ€ ์–ด๊ธ‹๋‚˜๋Š” ๋“ฏ ์‹ถ๋‹ค..


๐Ÿ“Œ 2. ๋ฌธ์ œ


125. Valid Palindrome (ํšŒ๋ฌธ ๋ฌธ์ž์—ด)


Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.


Input: s = โ€œA man, a plan, a canal: Panamaโ€ Output: true Explanation: โ€œamanaplanacanalpanamaโ€ is a palindrome.



โœ ํ’€์ด

var isPalindrome = function (s) {
  let answer = true;
  let lower = s.toLowerCase().replace(/[^a-z0-9+]/g, "");
  let num = lower.length / 2;
  for (let i = 0; i < num; i++) {
    if (lower[i] !== lower[lower.length - i - 1]) answer = false;
  }
  return answer;
};


  • ํšŒ๋ฌธ ๋ฌธ์ž ํ™•์ธ์‹œ ๊ฐ€์žฅ ๋จผ์ € ๋‚จ๊ฒจ์•ผ ํ•  ๋ฌธ์ž๊ฐ€ ์–ด๋–ค๊ฑด์ง€ ํ™•์ธ ํ›„ ์— ์ •๊ทœ์‹์œผ๋กœ ์ž‘์„ฑํ–ˆ๋‹ค. (์ตœ๊ทผ์— ์ •๊ทœํ‘œํ˜„์‹์„ ๊ณต๋ถ€ํ•˜๊ณ  ์žˆ๋Š”๋ฐ ํ›จ์”ฌ ํŽธํ•˜๋‹ค.) ๋ฌธ์ œ์—์„œ๋Š” ์˜,์ˆซ์ž๋ฅผ ๋ชจ๋‘ ํฌํ•จํ•ด์•ผํ•œ๋‹ค๊ณ  ํ•ด์„œ toLowerCase๋กœ ์ „์ฒด ๋ฌธ์ž์—ด์„ ์†Œ๋ฌธ์ž๋กœ ๋งŒ๋“ค๊ณ , replace(/[^a-z0-9+]/g,โ€โ€)๋กœ ์˜,์ˆซ์ž ์™ธ ๋ฌธ์ž๋Š” ์ œ๊ฑฐ ํ–ˆ๋‹ค.
  • ์ „์ฒด ๋ฌธ์ž์—ด์˜ ๋ฐ˜๋งŒ for๋ฌธ์œผ๋กœ ๋Œ๋ ค์„œ ์–‘์ชฝ ๋์˜ index๋ฅผ ๋ฝ‘์•„์„œ ๊ฐ™์€ ๋ฌธ์ž์ธ์ง€ ํ™•์ธํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ–ˆ๋‹ค.