Remove Element - LeetCode
Can you solve this real interview question? Remove Element - Given an integer array nums and an integer val, remove all occurrences of val in nums in-place [https://en.wikipedia.org/wiki/In-place_algorithm]. The order of the elements may be changed. Then r
leetcode.com
문제 설명
- 정수형 배열 nums가 주어진다.
- 비교할 정수 val이 주어진다.
- nums안의 수 중 val과 일치하지 않는 수를 nums배열의 앞에서부터 차례대로 저장해야 한다.
- nums안의 수 중 val과 일치하지 않는 경우의 수를 반환해야 한다.
- in-place 알고리즘을 사용해서 저장해야 한다.
문제 해결
- 반복문을 통해 배열의 각 수와 val의 값을 비교한다.
- 일치하지 않는 경우에 nums 배열에 인덱스 값을 answer로 한 자리에 일치하지 않는 수를 저장하고 answer값을 증가시킨다.
시간 복잡도
- O(N)
- N은 nums 배열의 크기이다.
- N = nums.length <= 100 이기 때문에 시간은 충분하다.
풀이 코드
class Solution {
public int removeElement(int[] nums, int val) {
int answer = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[answer++] = nums[i];
}
}
return answer;
}
}
결과
시간 | 메모리 |
0 ms | 40.7 MB |
'알고리즘 > LeetCode' 카테고리의 다른 글
[알고리즘] LeetCode - Best Time to Buy and Sell Stock (0) | 2023.08.25 |
---|---|
[알고리즘] LeetCode - Rotate Array (0) | 2023.08.25 |
[알고리즘] LeetCode - Majority Element (0) | 2023.08.24 |
[알고리즘] LeetCode - Remove Duplicates from Sorted Array II (0) | 2023.08.24 |
[알고리즘] LeetCode - Remove Duplicates from Sorted Array (0) | 2023.08.23 |