본문 바로가기
반응형

leetcode20

1389. Create Target Array in the Given Order 문제 nums 배열을 index 번호에 맞게 재배치 후 결과를 리턴하는 문제다. 내 현재 풀이 /** * @param {number[]} nums * @param {number[]} index * @return {number[]} */ var createTargetArray = function(nums, index) { let arr = []; for(let i in nums){ arr.splice(index[i],0,nums[i]) } return arr }; 새로운 배열에 담기 위해 arr를 만들었고, 배열에서 요소 추가 시 뒤예요 소들이 하나씩 뒤로 가야 하기 때문에 구글에 배열 추가를 검색했고, splice 함수를 발견해서 바로 적용해서 풀이했다. 내 예전 풀이 /** * @param {numbe.. 2022. 6. 9.
1528. Shuffle String 문제 스펠링을 indices에 숫자에 맞게 재배치해서 결과를 리턴한다. 내 현재 풀이 /** * @param {string} s * @param {number[]} indices * @return {string} */ var restoreString = function(s, indices) { let arr = [] for(let i in indices){ arr[indices[i]] = s[i] } return arr.join('') }; 처음에 생각한 방법 객체 형태로 만들어서 추출해보려 했데, 알파벳 e가 중복 때문에 원하는 방향으로 나오지 않았다. 그러고 나서 20분 정도 고민 후 새로운 배열에 indices안에 숫자를 그대로 이용해 배열의 순서 값으로 넣고 s의 요소들을 인덱스 번호대로 기입했다.. 2022. 6. 8.
1678. Goal Parser Interpretation 문제 주어진 command를 활용해 규칙에 맞게 변환해서 답을 리턴한다. G => G, () => o, (al) => al 이렇게 바꾸고 변환을 한다. 내 현재 풀이 /** * @param {string} command * @return {string} */ var interpret = function(command) { while(command.indexOf('()') > -1 || command.indexOf('(al)') > -1){ command =command.replace('()','o') command = command.replace('(al)','al') } return command }; indexOf를 통해 '()', '(al)'가 안 나올 때까지 진행하기 위해 while문을 활용했다... 2022. 6. 7.
1342. Number of Steps to Reduce a Number to Zero 문제 나머지가 0이 나올 때까지 나누기를 진행하고 나누기의 진행한 횟수를 체크 리턴하는 문제이다. 내 현재 풀이 /** * @param {number} num * @return {number} */ var numberOfSteps = function(num) { let cnt = 0 while(num > 0){ num %2 === 1 ? num-=1 : num /=2 cnt++ } return cnt; }; while문을 통해 num이 0 보다 큰 수까지 진행을 하고 홀수이면 -1 짝수이면 /2를 진행했다. 그리고 횟수 체크를 위해 cnt++를 했다. 내 예전 풀이 /** * @param {number} num * @return {number} */ var numberOfSteps = function (.. 2022. 6. 5.
1365. How Many Numbers Are Smaller Than the Current Number 문제 nums 안에 요소 하나씩 다른 요소들과 비교해서 비교 기준이 되는 인자보다 몇 개의 요소가 작은지 검사해 결괏값을 낸다. 내 현재 풀이 /** * @param {number[]} nums * @return {number[]} */ var smallerNumbersThanCurrent = function(nums) { let arr = [] let cnt = 0; for(let i of nums){ for( let j = 0; j nums[j]){ cnt++; } } arr.push(cnt) cnt = 0; } return arr }; 되게 단순하게 생각해 풀었다. 인자 하나씩 꺼내서 다음 for문을 통해 하나씩 비교한 후 배열에 담아 리턴했다. .. 2022. 6. 3.
1281. Subtract the Product and Sum of Digits of an Integer 문제 n의 요소를 하나씩 분리 후 곱한 결과와 더하기 한 결괏값을 빼기 후 그 값을 리턴하는 문제다. 내 현재 풀이 /** * @param {number} n * @return {number} */ var subtractProductAndSum = function(n) { n = n.toString(); n = n.split(''); let sum = n.reduce((a,c)=> a+Number(c),0) let product = n.reduce((a,c)=> a * Number(c),1) console.log(sum) return product - sum }; n이 처음에 int 형여서 split 함수를 사용하기 위해서 string 형으로 변환을 했다. 그다음 split를 사용해서 배열로 변환 후 r.. 2022. 6. 2.
반응형