| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
- queue
- bit
- c++
- event
- component
- array
- route
- UE5
- Props
- 비트연산
- nodeJS
- BinaryTree
- MySQL
- axios
- React
- server
- node.js
- leetcode
- Context
- count
- priority_queue
- DP
- JSX
- Callback
- Navigation
- treenode
- map
- routes
- state
- css
- Today
- Total
우사미 코딩
[Leetcode] 1027. Longest Arithmetic Subsequence 본문
1. 문제링크
https://leetcode.com/problems/longest-arithmetic-subsequence
Longest Arithmetic Subsequence - LeetCode
Can you solve this real interview question? Longest Arithmetic Subsequence - Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. Note that: * A subsequence is an array that can be derived from another array by
leetcode.com
2. 키포인트
- dp사용한다. dp란? 내가 이번에 풀 문제는 현재 직전까지의 풀이 기록으로 해결할 수 있다는 것임
map을 저장할 vector를 만들고 사이즈를 nums배열과 동일하게 한다.
nums = [3,6,9];
여기서 2중 for문을 돌건데
바깥 for문은 i = 0, i < nums.size() 까지, 안쪽 for문은 j = 0, j < i가 될 때까지 순회한다
그리고 두 인덱스 값의 차이를 map에 기록한다
diff가 v[j]에 있다면 v[i][diff] = v[j]+1한다
| i | j | diff | vector<un_map<int,int>> (i == j이면 업데이트 하지 않음) |
| 0 | 0 | - | - |
| 1 | 0 | 3 | v[1] = {3:2} |
| 1 | 1 | - | - |
| 2 | 0 | 6 | v[2] = {6:2} |
| 2 | 1 | 3 | v[2] = {6:2, 3:3} |
3. solution
class Solution {
public:
int longestArithSeqLength(vector<int>& nums) {
int res = 0;
int n = nums.size();
vector<unordered_map<int,int>> v(n);
for(int i = 0; i < n; i++){
for(int j = 0; j < i; j++){
if(i == j) continue;
int diff = nums[i] - nums[j];
if(v[j].count(diff)){
v[i][diff] = v[j][diff] + 1;
} else {
v[i][diff] = 2;
}
// cout << "v[" << i << "], diff : " << diff << ", v["<<i<<"] = {"<<diff<<":" << v[i][diff] <<"}"<< endl;
res = max(res, v[i][diff]);
}
}
return res;
}
};'Leetcode' 카테고리의 다른 글
| [Leetcode] 1466. Reorder Routes to Make All Paths Lead to the City Zero (0) | 2023.06.23 |
|---|---|
| [Leetcode] 1143. Longest Common Subsequence (0) | 2023.06.22 |
| [Leetcode] 2090. K Radius Subarray Averages (0) | 2023.06.21 |
| [LeetCode] 450. Delete Node in a BST (0) | 2023.06.20 |
| [Leetcode] 2542. Maximum Subsequence Score (0) | 2023.06.18 |