[LeetCode] 1299. Replace Elements with Greatest Element on Right Side, Easy
·
CodingTest/LeetCode
1. 문제배열 arr이 주어질 때, 0번 인덱스 부터 오른쪽에 위치한 값들 중 제일 높은 값으로 바꾸어 반환하라.마지막 요소는 -1로 채운다.2. 해결function replaceElements(arr: number[]): number[] { if(arr.length === 1) { // 요소가 1개만 있는 경우 -1로 채우고 반환. arr[arr.length-1] = -1; return arr; } let max = 0; // 최대값 저장. for(let i = arr.length - 1; i >= 0; i--) { // 뒤에서 부터 반복. if(i === arr.length - 1) { // 마지막 요소는 max를 업데이트하고 -1로 업..
[LeetCode] 941. Valid Mountain Array, Easy
·
CodingTest/LeetCode
1. 문제배열 arr이 주어질 때, 다음 조건을 만족하면 true, 아니면 false를 반환.배열 길이는 3이상이어야 한다.0번 인덱스부터 특정 인덱스 기준까지 요소의 값이 상승해야 한다.특정 인덱스 기준부터 요소의 값이 하락해야 한다.2. 해결function validMountainArray(arr: number[]): boolean { if(arr.length arr[i]) continue; else if(arr[i+1] 첫 풀이다. 방향을 나타내는 dir과 특정 인덱스에 도달했는지 여부를 변수로 빼고, 배열의 처음 부터 탐색하면서 방향과 인덱스 도달 여부를 업데이트 해준다.값이 상승하는 중에 하락하거나, 하락 중에 상승하면 false를 반환하고, 그렇지 않으면 특정 인덱스..
[LeetCode] 1346. Check If N and Its Double Exist, Easy
·
CodingTest/LeetCode
1. 문제배열 arr이 주어질 때, i와 j에 대해 조건을 만족하는지 여부를 반환하라. 2. 해결function checkIfExist(arr: number[]): boolean { for(let i = 0; i조건에 맞게 구현하면 된다.function checkIfExist(arr: number[]): boolean { const values = new Set(); for (let i=0; i 이건 다른 사람 풀이인데, 중복을 없애는 Set에 집어 넣고, O(n) 시간에 조건을 판별할 수 있더라.
[LeetCode] 26. Remove Duplicates from Sorted Array, Easy
·
CodingTest/LeetCode
1. 문제배열 nums가 오름차순으로 정렬되어 주어질 때, 해당 배열을 수정하여 모든 요소 중 각각 1개 씩만 맨 앞에 정렬하고, 그 길이를 반환하라.2. 풀이function removeDuplicates(nums: number[]): number { let compIndex = 0; // 비교 인덱스 let index = 0; // 배열 탐색 인덱스 let result = 1; // 총 길이 // 비교 인덱스가 배열의 마지막에 도달하기 전까지 반복. while(compIndex 마찬가지로 투 포인터로 풀 수 있다.for문을 이용해보려고 했는데, 코드가 깔끔하지 않아서 while문을 쓰니까 깔끔히 정리됐다.
[LeetCode] 27. Remove Element, Easy
·
CodingTest/LeetCode
1. 문제배열 nums와 값 val이 주어질 때, val와 일치하지 않는 요소들을 nums 배열 앞에 나열한 뒤, 길이를 반환하라.val와 일치하지 않는 요소들을 앞에 나열 시킬 때, 순서는 상관없고 이후에 어떤 요소가 오든 상관없다.2. 해결function removeElement(nums: number[], val: number): number { let index = 0; let end_index = nums.length -1; while (index index) end_index--; if(nums[index] === val) { nums[index] = nums[end_index]; nums[end_index] ..
[LeetCode] 88. Merge Sorted Array, Easy
·
CodingTest/LeetCode
1. 문제배열 nums1, nums2가 주어지고, 각각의 길이 m과 n이 주어질 때, 두 배열의 요소를 오름차순으로 정렬하여 nums1 배열에 채워라.단, nums1 배열은 m+n 길이를 가지고, m만큼은 요소가 채워져있고 나머지 n은 0으로 채워져 있다. 이는 nums2의 길이와 같다.2. 풀이/** Do not return anything, modify nums1 in-place instead. */function merge(nums1: number[], m: number, nums2: number[], n: number): void { let index_1 = m-1; // nums1을 가리키는 포인터 let index_2 = n-1; // nums2를 가리키는 포인터 for..
[LeetCode] 1089. Duplicate Zeros, Easy
·
CodingTest/LeetCode
1. 문제고정 배열 arr이 주어질 때, 요소 중 0이 나오면 바로 다음 요소에 복제하고, 기존 요소들은 1칸 씩 뒤로 밀려진 배열을 구성하라.새로운 배열을 사용하지 말고, 처음 제공되는 arr 배열을 수정하라. 배열 반환 X.2. 해결/** Do not return anything, modify arr in-place instead. */function duplicateZeros(arr: number[]): void { let index = 0; while(index = arr.length-2) { for(let i = index; i index; i--) { arr[i+1] = arr[i] if(i === index..
[LeetCode] 977. Squares of a Sorted Array, Easy
·
CodingTest/LeetCode
1. 문제오름차순으로 정렬된 배열이 주어질 때, 각 요소를 제곱한 뒤에도 오름차순을 유지하는 배열을 반환하라.2. 해결function sortedSquares(nums: number[]): number[] { const result = nums.map(num => Math.pow(num, 2)) result.sort((a,b) => a-b); return result;};우선, 문제를 보자마자 떠올린 방법이다. 단순히 모든 배열을 순환하며 제곱하고, 해당 배열을 정렬한다.이 경우, O(NlogN) 시간 복잡도가 나온다.function sortedSquares(nums: number[]): number[] { const result = new Array(nums...
[LeetCode] 1295. Find Numbers with Even Number of Digits, Easy
·
CodingTest/LeetCode
1. 문제정수로 구성된 배열이 주어질 때, 각 요소의 수가 짝수 자리수로 구성된 개수를 반환.ex) 12 -> 1과2 짝수 자리 수, 123 -> 1, 2, 3 홀수 자리 수2. 해결function findNumbers(nums: number[]): number { const result = nums.reduce((acc : number, current) => { const isEvenDigit = String(current).split('').length % 2 === 0 ? true : false; if(isEvenDigit) acc+=1; return acc; }, 0) return result;};어쨋든 모든 요소를 판단해야 하니까 다 ..
[LeetCode] 485. Max Consecutive Ones, Easy
·
CodingTest/LeetCode
1. 문제0과 1로 이루어진 배열이 주어질 때, 연속된 1이 가장 많이 나오는 횟수는?2. 해결type AccType = {max: number; value :number; prev: number | null}function findMaxConsecutiveOnes(nums: number[]): number { const result = nums.reduce((acc: AccType, current) => { acc.value += current; if(current === 0 && acc.value !== 0) { acc.max = Math.max(acc.max, acc.value); acc.value = 0; ..