[LeetCode] 8.Remove Element
leetcode.com/problems/remove-element/
1. Problem
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy) int len = removeElement(nums, val); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); }
Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted.
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3]
Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.
Constraints:
- 0 <= nums.length <= 100
- 0 <= nums[i] <= 50
- 0 <= val <= 100
2. Code
package leetCode;
import java.util.ArrayList;
public class RemoveElement {
final static int[] nums = {3,2,2,3};
public static void main(String[] args) {
int val = 3;
}
public static int removeElement(int[] nums, int val) {
ArrayList<Integer> numsList = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++) {
if(nums[i] != val) {
numsList.add(nums[i]);
}
}
int[] newNums = new int[numsList.size()];
for(int i = 0; i < numsList.size(); i++) {
nums[i] = numsList.get(i);
}
return numsList.size();
}
}
3. Report
이 문제는 전역변수로 선언되어 있는 nums배열을 변경해야 한다.
처음에 newNums에 값을 제거한 새로운 배열을 생성하고
nums = newNums; 로 변경하려고 했는데 주소값이 달라서 제대로 변경되지 않았다.
이 문제는 진짜 제거된 배열을 출력하는게 목적이 아니라
nums에서 val값을 뒤로 보낸 후
배열에서 val값을 제외한 크기 만큼만 출력하면 된다.
그래서 나는 그냥 3, 2, 2, 3을 2, 2, 3, 3 이 아닌
2, 2, 2, 3으로 바꿨다
출력부분까지만 제대로 나오면 될것같다~
'Algorithm > 문제' 카테고리의 다른 글
[LeetCode] 10.Remove Duplicates from Sorted ArrayⅡ (0) | 2021.01.04 |
---|---|
[LeetCode] 9.Remove Duplicates from Sorted Array (0) | 2021.01.04 |
[LeetCode] 7.Longest Common Prefix (0) | 2020.12.30 |
[LeetCode] 6.Merge Two SortedLists (0) | 2020.12.30 |
[LeetCode] 5.Palindrome Number (0) | 2020.12.29 |