반응형
https://leetcode.com/problems/remove-element/
Remove Element - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
간단 전수조사 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
n이 작기 때문에 2차원 loop를 수행해 정렬해도 됩니다.
📔 풀이과정
지울 수를 배열의 뒷편에 배치시키는 swap문제라고 생각해봅니다.
앞의 val이 있다면 그 이후부터 for loop를 수행하며 val이 아닌 원소를 찾아 swap을 해주면 됩니다.
📔 정답출력
val이 아닌 원소들의 길이를 반환해줍니다.
📕 Code
📔 C++
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != val) continue;
for(int j = i+1; j < nums.size(); j++){
if(nums[j] == val) continue;
swap(nums[i], nums[j]);
break;
}
}
int cnt = 0;
for(auto n: nums) {
if(n == val) break;
cnt++;
}
return cnt;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Brute Force' 카테고리의 다른 글
(C++) - LeetCode (easy) 1072. Flip Columns For Maximum Number of Equal Rows (0) | 2023.02.01 |
---|---|
(C++) - LeetCode (easy) 268. Missing Number (0) | 2023.01.27 |
(C++) - LeetCode (easy) 14. Longest Common Prefix (1) | 2022.10.13 |
(C++, Rust) - 백준(BOJ) 13225 : Divisors (0) | 2022.09.10 |
(Rust) - 백준(BOJ) 23348 : 스트릿 코딩 파이터 (0) | 2022.08.27 |