- Today
- Total
- ꡬν
- tree
- BFS
- 벨λ§ν¬λ
- νλ‘κ·Έλλ¨Έμ€
- spring
- PS
- λ¬Έλ²
- μμμ λ ¬
- java
- OOP
- database
- MST
- λ€μ΅μ€νΈλΌ
- pytorch
- dp
- leetcode
- λ°±μ€
- Algorithm
- λ°±μλ
- Graph
- μλ°μμ μ
- array
- λ°μ΄ν°λ² μ΄μ€
- 그리λ
- μΈν΄
- μ‘Έμ μν
- μλ£κ΅¬μ‘°
- CS
- μλ°
Partially Committed
[Algorithm] Subsequence νλ³νκΈ° λ³Έλ¬Έ
[Algorithm] Subsequence νλ³νκΈ°
WonderJay 2022. 10. 23. 21:07μ€λμ λ³΄λ€ κ°λ¨ν μν©μ λν΄μ 곡λΆν΄λ³΄μ. λ°λ‘ Subsequence νλ¨ λ¬Έμ μΈλ°, Subsequence μ μ μλ μλμ κ°λ€.
In mathematics, a subsequence of a given sequence is a sequence that can be derived from the given sequence by deleting some or no elements without changing the order of the remaining elements. - wiki
λ°°μ΄μ΄ μ£Όμ΄μ‘λ€κ³ κ°μ νλ©΄, μμμ μμλ₯Ό λ°κΎΈλ νμ μμ΄ μΌλΆ μμλ§ delete νμ¬ origin array λ‘λΆν° subsequence μ λ§λ€μ΄λΌ μ μλ€. μλ₯Ό λ€μ΄ [1,5,7,9] μ λν΄μ [1, 5], [1,7], [1,9], [5,7] μ κ°μ subsequence κ° μ‘΄μ¬νλ€. μ½λ©ν μ€νΈ λ¬Έμ μμ νΉμ λ©΄μ μμ origin array μ candidate array κ° μμ λ, candidate array κ° origin array μ subsequence μΈμ§ μλμ§λ₯Ό μ΄λ»κ² νλ¨ν μ μκ² λλκ³ λ¬Όμ΄λ³Ό μ μλ€. μ΄λ»κ² ν΄κ²°ν μ μμκΉ?
μ루μ μ λ¨μνλ€. origin array λ₯Ό 1λ² μννλ κ²λ§μΌλ‘ νλ³μ΄ κ°λ₯νλ€. origin array μ candidate array μ position μ λνλ΄λ λ³μλ₯Ό κ°κ° array_idx, sequence_idx λΌκ³ μ μ₯ν λ€μμ origin array λ₯Ό μννλ©΄μ origin_array[array_idx] == candidate_array[sequence_idx] λΌλ©΄ sequence_idx λ₯Ό νλ μ¦κ°μν¨λ€. origin_array λ₯Ό λͺ¨λ μννκ±°λ sequence_idx κ° candidate_array.size() μ κ°μμ§λ©΄ ν΄λΉ loop λ₯Ό νμΆνλ€. loop λ₯Ό νμΆνμ λ, sequence_idx == candidate_array_size() λΌλ©΄ true λ₯Ό, λ€λ₯΄λ€λ©΄ false λ₯Ό λ°ννμ¬ subseuqence μΈμ§ μλμ§ νλ³νλ μκ³ λ¦¬μ¦μ κ°λ¨νκ² κ΅¬νν μ μλ€.
origin array λ₯Ό 1νλ§ μννλ©΄ λλ―λ‘ μκ° λ³΅μ‘λλ O(N) μ΄κ³ , κ³΅κ° λ³΅μ‘λλ O(1) μ΄λ€.
[solution1]
using namespace std;
// time : O(N)
// space : O(1)
bool isValidSubsequence(vector<int> array, vector<int> sequence) {
// Write your code here.
int array_idx = 0;
int sequence_idx = 0;
while(array_idx < array.size() && sequence_idx < sequence.size()){
if(array[array_idx] == sequence[sequence_idx]){
sequence_idx++;
}
array_idx++;
}
return sequence_idx == sequence.size();
}
[solution2]
using namespace std;
// time : O(N)
// space : O(1)
bool isValidSubsequence(vector<int> array, vector<int> sequence) {
// Write your code here.
int sequence_idx = 0;
for(int i = 0 ; i <array.size(); i++){
if(sequence_idx == sequence.size())
break;
if(sequence[sequence_idx] == array[i])
sequence_idx++;
}
return sequence_idx == sequence.size();
}
https://github.com/versatile0010/AlgoExpert
'π₯ Algorithm || λ¬Έμ νμ΄ > PS' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[Algorithm] Tournament Winner (0) | 2022.10.25 |
---|---|
[Algorithm] Sorted squared array λ°ννκΈ° (0) | 2022.10.24 |
[Algorithm] λ°°μ΄ λ΄, νΉμ 쑰건μ λ§μ‘±νλ μμ μ κ²μνκΈ° (0) | 2022.10.22 |
[LEETCODE] 496. Next Greater Element I (0) | 2022.10.14 |
[LEETCODE] 1790. Check if One String Swap Can Make Strings Equal (0) | 2022.10.13 |