remove-duplicates-from-sorted-array
리트코드 동아리가 오늘 생겼다고 해서, 뒤늦게 해보고 있다. 나는 TypeScript로 도전...
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
먼저 짰던 코드는 요거
function removeDuplicates(nums: number[]): number
{
let i: number;
let j: number;
i = 0;
j = 1;
for (j; j < nums.length; j++)
if (nums[i] != nums[j])
nums[++i] = nums[j];
return i + 1;
};
이걸 위해서... 기본 프로토타입은 주어졌으니, TS와 JS 매뉴얼을 읽어가며 이해하는데 좀 시간이 걸렸다.
- 선언한 변수 뒤에 : (콜론)을 붙여 타입을 정의해서 타입스크립트인 것 같다.
- 변수 선언은 let으로, 기존의 var 보다 안전함.
https://www.typescriptlang.org/docs/handbook/basic-types.html
Basic Types · TypeScript
Table of Contents # Introduction Boolean Number String Array Tuple Enum Any Void Null and Undefined Never Object Type assertions A note about ‘let’ Introduction # For programs to be useful, we need to be able to work with some of the simplest units of
www.typescriptlang.org
하지만 Array에 대해 slice란 함수가 있어서, 다시 시도... 했으나 문제풀이에는 못 씀
원본은 그대로 둔 채, 본을 뜨는 작업. 그러니까 C로 이해하면 일부분을 duplicate하는 거 같은데 생각보다 코드가 잘 안돌아서 접음
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
Array.prototype.slice()
slice() 메서드는 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.
developer.mozilla.org
이거는 비교연산자 '===' 타입까지 비교한다고 한다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
비교 연산자
JavaScript는 엄격한 비교와 형변환 비교 두 가지의 비교 방법을 모두 가지고 있습니다. 엄격(일치) 비교(===)는 두 피연산자가 같은 자료형에, 그 내용도 일치해야만 참입니다. 추상(동등) 비교(==)는
developer.mozilla.org
for ~ of 반복문, 쓰는 걸봐서는 for in 보다 나은 듯
https://victorydntmd.tistory.com/89
[JS] for in와 for of 비교 - Iteration
2019. 06. 09 수정 1. Iteration이란? Iteration이란 사전적 의미로 "되풀이"를 의미하며, while문, for문과 같은 문법을 Iteration이라 합니다. 일반적으로 아래와 같이 Array를 반복문으로 돌립니다. let arr..
victorydntmd.tistory.com
function removeDuplicates(nums: number[]): number {
let curElm: number;
let nextIdx: number;
let n: number;
n = nums.length;
curElm = nums[0];
nextIdx = 1;
for (let num of nums.slice(1)) {
if (curElm === num){
continue;
}
curElm = num;
nums[nextIdx] = curElm;
nextIdx++;
}
nums = nums.slice(0, nextIdx);
return nums.length;
};
위에 코드는 이해만 하고 넘어가자.
'Problem Solving' 카테고리의 다른 글
[boj] 10953 A+B - 6 (0) | 2020.11.23 |
---|---|
[boj] 10952 A+B - 5 (0) | 2020.11.23 |
[boj] 10951 A+B - 4 (0) | 2020.11.23 |
[boj] 15552 빠른 A+B (0) | 2020.11.23 |
best-time-to-buy-and-sell-stock-II (DP 알고리즘) (0) | 2020.07.10 |