관리 메뉴

Partially Committed

[Algorithm] Subsequence νŒλ³„ν•˜κΈ° λ³Έλ¬Έ

πŸ”₯ Algorithm || λ¬Έμ œν’€μ΄/PS

[Algorithm] Subsequence νŒλ³„ν•˜κΈ°

WonderJay 2022. 10. 23. 21:07
728x90
λ°˜μ‘ν˜•
SMALL

  μ˜€λŠ˜μ€ 보닀 κ°„λ‹¨ν•œ 상황에 λŒ€ν•΄μ„œ κ³΅λΆ€ν•΄λ³΄μž. λ°”λ‘œ Subsequence νŒλ‹¨ 문제인데, Subsequence 의 μ •μ˜λŠ” μ•„λž˜μ™€ κ°™λ‹€.

https://en.wikipedia.org/wiki/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

 

GitHub - versatile0010/AlgoExpert: Solutions to AlgoExpert Problems.

Solutions to AlgoExpert Problems. Contribute to versatile0010/AlgoExpert development by creating an account on GitHub.

github.com

 

728x90
λ°˜μ‘ν˜•
LIST
Comments