LeetCode - 27. Remove Element(Array, Two Pointers)*

YAMAMAMO·2022년 1월 27일
0

LeetCode

목록 보기
6/100

문제

https://leetcode.com/problems/remove-element/submissions/

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

번역 파파고(일부수정)
정수 배열 Num과 정수 val이 주어지면 num의 모든 val을 in-place에서 제거합니다. 원소의 상대적인 순서가 변경될 수 있습니다.

일부 언어에서는 배열 길이를 변경할 수 없으므로 결과를 배열 번호의 첫 번째 부분에 배치해야 합니다. 더 형식적으로, 중복을 제거한 후에 k개의 원소가 있다면, 숫자의 첫 번째 k개의 원소는 최종 결과를 가져야 한다. 첫 번째 k 원소 뒤에 무엇을 남겨두든 중요하지 않습니다.

첫 번째 k개의 숫자 슬롯에 최종 결과를 넣은 후 k를 반환합니다.

다른 배열에 추가 공간을 할당하지 마십시오. O(1) 추가 메모리로 입력 배열을 수정하여 이 작업을 수행해야 합니다.

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,,]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).

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 k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

풀이

자바입니다.
1. result를 배열의 크기로 받는다.
2. nums[i]가 val 과 같으면 배열의 마지막 값으로 변경한다.
3. result-- 한다.(배열의 크기를 줄인다.)
4. i--(배열의 값이 변경되면 그 위치에서 다시 반복문이 돌아야한다.)
5. result를 리턴한다.

class Solution {
    public int removeElement(int[] nums, int val) {
        int result=nums.length;
        for(int i=0;i<result;i++){
            if(nums[i]==val){ 
                nums[i]=nums[result-1];
                result--;
                i--;   
            }
        }
        return result;
    }
}
profile
안드로이드 개발자

0개의 댓글