๐ 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๋ฅผ ๋ฝ์์ ๊ฐ์ ๋ฌธ์์ธ์ง ํ์ธํ๋ ๋ฐฉ์์ผ๋ก ์ฝ๋๋ฅผ ์์ฑํ๋ค.