https://leetcode.com/explore/interview/card/top-interview-questions-easy/
leetcode top interview questions - easy collection을 풀면서 기록
Array
Rotate Image
https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/770/
in-place, which means you have to modify the input 2D matrix directly. Do NOT allocate another 2D matrix and do the rotation.
in-place algorithm은 input data structure에 비례하는 추가 공간을 필요로 하지 않고, input data structure에서 직접 동작하는 알고리즘을 말한다. (즉, data structure의 별도 사본을 생성하지 않고 이미 할당된 input data structure로만 해결한다.)
행렬에서 in-place 문제라면 일대일 swap 하라는 의미가 된다.
(행이나 열을 단위로 swap 한다면 추가적인 data structure가 필요하니까)
문제를 언뜻 보면 일대일 swap으로 규칙이 보이지 않지만,
일대일 swap을 2번 거치면 정답을 만들 수 있는 규칙이 있다.
1. 중간 행을 기준으로 뒤집기
2. 대각선을 기준으로 뒤집기(전치행렬)
or
1. 전치행렬
2. 행 안에서 순서 뒤집기
문제 포인트: 행렬 in-place라면 일대일 swap을 의미하고, 규칙이 안 보이면 몇 번의 swap을 거치는 방법으로 접근하자.
Strings
Reverse Integer
https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/880/
If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
64-bit 정수 저장을 허용하지 않는다고 가정한다 = long을 사용하지 말아라.
point 1.
long을 사용하지 않고 int 값이 32비트 정수를 넘었는지 잡으려면?
int 값을 업데이트하기 전에 확인한다.
class Solution {
public int reverse(int x) {
int y = 0;
while (x!=0) {
int digit = x % 10;
x /= 10;
if (y > (Math.pow(2, 31)-1)/10 || y < (Math.pow(-2, 31))/10) return 0;
y = y * 10 + digit;
}
return y;
}
}
범위(-2^31 ~ 2^31 - 1)에 업데이트할 값을 미리 반영하면, int 값을 업데이트 하기 전에 오버플로우인지 아닌지 알 수 있다.
point 2.
그리고 123을 뒤집을 때, 300 + 20 + 1 이런 로직을 접근했는데
(이 로직은 처음에 자릿수 길이 구해야 함)
위 풀이처럼
1 step = 3
2 step = (3) * 10 + 2
3 step = (32) * 10 + 1
이렇게 접근할 수도 있다.
계속 추가
'Algorithm > Leetcode' 카테고리의 다른 글
릿코드 2. Add Two Numbers, 49. Group Anagrams (0) | 2024.02.17 |
---|---|
릿코드 134. Gas Station, 135. Candy (2) | 2024.02.09 |
릿코드 238. Product of Array Except Self (0) | 2024.02.06 |
릿코드 45. Jump Game II (0) | 2024.02.04 |
릿코드 55. Jump Game (2) | 2024.02.02 |