LeetCode - Two Pointer 문제들 회고

jinvicky·2024년 10월 2일
0

Algorithm - Java

목록 보기
63/63
post-thumbnail

two pointer 알고리즘을 easy, medium을 번갈아 가면서 풀고 있는데 기억해두고 싶은 것들을 간단히 적어보았다.

125

문자열이 회문수인지를 체크하는 문제에서 특수문자나 공백이 중간에 낀 경우 이를 제외하고 주어진 알파벳 문자열이 회문수인지 체크해야 한다.

나의 경우 테스트 케이스를 어떻게든 통과하기 위해 테스트 케이스를 돌려가면서 모든 특수문자들을 s.replace()하는 행동을 했다;;

📌 어떻게 개선할까 solution들을 보면서 되짚어 보았더니
Character가 영문자 또는 숫자인지 검사하는 로직으로 처리하더라.
isLetterOrDigit()이라는 라이브러리 메서드로 처리할 수 있다.

if(!Character.isLetterOrDigit(currFirst)) {
                start++;
            } else if (!Character.isLetterOrDigit(currLast)) {
                last--;
                // 위 까지가 특수문자 필터링
            }

977

977번 문제의 경우 음수부터 양수까지 배열이 주어지면
절댓값을 구했을 때 중간보다 왼쪽의 값이 더 크다. 때로는 오른쪽 맨 끝 값보다 더 클 수도 있다.

그 경우에 오름차순으로 제곱값을 출력하려면 left와 right의 절댓값을 비교해서 결과 배열을 뒤에서부터 채운다.

다만 left, right에 따라서 start, end 포인터의 증감 여부가 달라질 것이다.


 if(Math.abs(nums[start]) > Math.abs(nums[end])) {
        ans[size-1] = nums[start]*nums[start]; 
        start++;
    } else {
        ans[size-1] = nums[end]*nums[end];
        end--;
    }
    size--;

Problems

Easy
Two Sum II - Input array is sorted

문제 번호: 167
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
Move Zeroes

문제 번호: 283
https://leetcode.com/problems/move-zeroes/
Valid Palindrome

문제 번호: 125
https://leetcode.com/problems/valid-palindrome/
Intersection of Two Arrays II

문제 번호: 350
https://leetcode.com/problems/intersection-of-two-arrays-ii/
Valid Anagram

문제 번호: 242
https://leetcode.com/problems/valid-anagram/
Squares of a Sorted Array

문제 번호: 977
https://leetcode.com/problems/squares-of-a-sorted-array/

profile
Front-End와 Back-End 경험, 지식을 공유합니다.

0개의 댓글